我正在使用Python 2.7和PySide 1.2.1,并需要一个小部件来绘制有颜色的背景。在Qt Designer中,我创建了一个简单的窗口,包含一个标签、一个包含三个其他项目的小部件和另一个标签。对于包含按钮、单选框和复选框的小部件,我将
styleSheet
属性设置为background-color: #FFFFFF
。在Qt Designer中,所有内容都按预期呈现:但是在Pyside中,小部件没有绘制背景颜色,但其上的项目正确继承了颜色:以下是ui-XML:<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>276</width>
<height>133</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QVBoxLayout" name="verticalLayout" stretch="0,1,1">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>The following should have white background:</string>
</property>
</widget>
</item>
<item>
<widget class="QWidget" name="widget" native="true">
<property name="styleSheet">
<string notr="true">background-color: #FFFFFF</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>PushButton</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioButton">
<property name="text">
<string>RadioButton</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBox">
<property name="text">
<string>CheckBox</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>But it hasn't :-(</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>276</width>
<height>18</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
以下是我的 Python 代码,没有什么特别的:
import sys
from PySide import QtCore, QtGui
from generated.test import Ui_MainWindow
class MainWindow(Ui_MainWindow,QtCore.QObject):
def __init__(self, *args, **kwargs):
Ui_MainWindow.__init__(self, *args, **kwargs)
QtCore.QObject.__init__(self)
def setupUi(self, MainWindow):
Ui_MainWindow.setupUi(self, MainWindow)
def main(argv):
app = QtGui.QApplication(argv)
mainwindow = QtGui.QMainWindow()
ui = MainWindow()
ui.setupUi(mainwindow)
mainwindow.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main(sys.argv)
我已经尝试过self.widget.setAutoFillBackground(True)
,但是根据文档,只要背景有一个有效的styleSheet值,这个属性就会被禁用。
这也不起作用:
p = self.widget.palette()
p.setColor(self.widget.backgroundRole(), QtCore.Qt.white)
self.widget.setPalette(p)
(这些提示来自如何设置QWidget背景颜色?)
我该如何让窗口小部件绘制白色背景颜色?
WA_StyledBackground
属性在QWidget()
和QLabel
中的testAttribute()
方法中都没有设置,但第一个需要设置以绘制样式化背景,而第二个则不需要?(我刚刚测试过。) - Trilarion