未应用嵌套自定义小部件的样式表 [英] Stylesheet for nested custom widget not applied
问题描述
我希望以下代码在外部主窗口内显示一个小的黑色区域:
I expect the following code to show a small black area inside outer main window:
class Canvas(QWidget):
pass
app = QApplication(sys.argv)
outer = QWidget()
w = Canvas(outer)
w.setStyleSheet("background-color: black")
outer.show()
但是看起来样式表没有被应用:整个外部窗口都是灰色的.但是,如果 w
是 QWidget
,代码会按预期工作.当 Canvas
实例直接显示(没有父级)时,样式表也被正确应用:
But looks like the stylesheet is not applied: entire outer window is gray.
However, if w
is a QWidget
, code works as expected. When Canvas
instance is shown directly (without parent) stylesheet is properly applied as well:
w = Canvas()
w.setStyleSheet("background-color: black")
w.show()
此代码显示一个黑色窗口.我在 C++ 中使用 Qt 4.8.6 进行了相同的尝试,样式表也正确应用于从 QWidget 派生的嵌套小部件.
This code shows a black window. I have tried same in C++ with Qt 4.8.6 and stylesheet is also properly applied for nested widgets derived from QWidget.
我错过了什么?我在 Ubuntu 14.04 下使用 python 2.7.6、Qt 4.8.6 和 PyQt 4.10.4.
What am I missing? I am using python 2.7.6, Qt 4.8.6 and PyQt 4.10.4 under Ubuntu 14.04.
推荐答案
QWidget
子类默认会忽略样式表(出于性能原因).
A QWidget
subclass will ignore stylesheets by default (for performance reasons).
试试这个:
w = Canvas(outer)
w.setAttribute(QtCore.Qt.WA_StyledBackground)
w.setStyleSheet("background-color: black")
这篇关于未应用嵌套自定义小部件的样式表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!