【发布时间】:2014-08-30 11:06:13
【问题描述】:
我使用 Qt4.8 Python 绑定 PySide(Windows 上 Python 3.3 上的版本 1.2.2),我看到 QWidget 的行为不同于 QWidgetderived 小部件,如 QDialog、QLabel 或 QMainWindow使用样式表进行样式设置时。
我特别观察到属性WA_StyledBackground 必须设置为显示边框或背景图像,而背景颜色是独立设置的。与其他小部件相比,此属性没有影响,始终显示边框或背景图像。也可以覆盖paintEvent 方法。
示例代码:
from PySide import QtGui, QtCore
class MyWidget(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def paintEvent(self, event):
opt = QtGui.QStyleOption()
opt.initFrom(self)
painter = QtGui.QStylePainter(self)
painter.drawPrimitive(QtGui.QStyle.PE_Widget, opt)
def display(w):
print(w.__class__.__name__)
w.setWindowTitle(w.__class__.__name__)
print(' WA_StyledBackground is {}'.format(w.testAttribute(QtCore.Qt.WA_StyledBackground)))
print(' autoFillBackground is {}'.format(w.autoFillBackground()))
w.setStyleSheet('border: 4px inset #515c84; border-radius: 9px; background-color: blue; background-image: url(test.png);')
w.resize(400, 400)
w.show()
app = QtGui.QApplication([])
w1 = QtGui.QMainWindow(flags=QtCore.Qt.Window)
display(w1) # works
w2 = QtGui.QDialog(f=QtCore.Qt.Window)
display(w2) # works
w3 = QtGui.QWidget(f=QtCore.Qt.Window)
w3.setAttribute(QtCore.Qt.WA_StyledBackground)
display(w3) # works only with the previous line uncommented
w4 = QtGui.QLabel('Text', f=QtCore.Qt.Window)
display(w4) # works
w5 = MyWidget(f=QtCore.Qt.Window)
display(w5) # works
app.exec_()
该主题已在 StackOverflow 上进行了部分讨论。 Borders and background of QWidget aren't set by stylesheet 上接受的答案建议覆盖paintEvent,How to set QWidget background color? 接受的答案建议设置setAutoFillBackground,以防有人使用调色板,PySide: QWidget does not draw background color 建议只设置上述WA_StyledBackground。缺少的是QWidget 和派生小部件之间差异的原因。
我觉得这些差异有点令人困惑:
- 为什么
QWidget的行为与QLabel、...等派生小部件的行为不同? - 为什么
QWidget在自然状态下不显示边框或背景图片,却显示背景颜色? - 以上述方式设置属性
WA_StyledBackground和覆盖paintEvent有区别吗?首选哪种方法?
【问题讨论】:
标签: qt background stylesheet pyside qwidget