问题描述
我的代码生成一个包含两个 qwidget 的窗口,一个红色 (wg1) 和一个蓝色 (wg2).如果它们变成继承自 qwidget 的 fields(注释掉),它们的颜色就会消失.
my code generates a window containing two qwidgets, a red (wg1) and a blue (wg2) one. if they become fields (commented out) which inherits from qwidget, their color disappears.
我的问题是:为什么 field(继承自 qwidget)需要有一行
my question is: why is it necessary for a field (which inherits from qwidget), to have the line
self.setattribute(qt.wa_styledbackground, true)
在它的 __init__ 方法中,而 qwidget 不需要这一行?
in its __init__-method while a qwidget doesn't need this line?
import sys from pyqt5 import qtwidgets from pyqt5.qtwidgets import qwidget, qapplication, qgridlayout from pyqt5.qtcore import qt class field(qwidget): def __init__(self, name): super().__init__() self.name = name # self.setattribute(qt.wa_styledbackground, true)# !!! def mousepressevent(self, event): print(f" click makes {self.name} green") self.setstylesheet("background: #00ff00;") if __name__ == "__main__": app = qapplication(sys.argv) root = qwidget() grid = qgridlayout() root.setlayout(grid) root.resize(300,100) wg1 = qwidget() wg2 = qwidget() # wg1 = field('wg1') # wg2 = field('wg2') wg1.setstylesheet("background: #aa1111;") grid.addwidget(wg1, 0, 0) wg2.setstylesheet("background: #1111aa;") grid.addwidget(wg2, 0, 2) root.show() sys.exit(app.exec_())
推荐答案
解释在样式表参考中与 qwidget 相关的部分:
如果您从 qwidget 继承,您需要为您的自定义 qwidget 提供一个paintevent,如下所示:
if you subclass from qwidget, you need to provide a paintevent for your custom qwidget as below:
默认情况下,qwidget 会默认执行此操作,但 qwidget 子类不会,因此您要么设置标志,要么实现paintevent.
by default, qwidget does that by default, but qwidget subclasses do not, so you either set the flag or you implement the paintevent.
无论如何,请考虑使用 样式表选择器 并避免通用/通用语法,因为它们通常会导致复杂的子小部件出现意外行为.
in any case, consider using stylesheet selectors and avoid generic/universal syntax as they often result in unexpected behavior for complex child widgets.