问题
I spent some time struggling to use .setStyleSheet
to change the background color of a QWidget used as a window, using Python 3.5.2, PyQt 5.9 and Qt 5.9.1. I tried various suggestions I found online, but what ended up working was changing the object name of the QWidget, referring afterwards to that name as an ID in the stylesheet.
My question is, is this behaviour I can rely on, or is there an alternative way of doing it?
Working code:
#!/usr/bin/python3
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QApplication)
class BgColorExperiment(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
QLabel('some words 一些單詞', self).move(20, 0)
self.setObjectName('MainWidget')
self.setStyleSheet("""
#MainWidget {
background-color: #333;
}
.QLabel {
color: #fff;
}
""")
self.setGeometry(300, 300, 350, 100)
self.setWindowTitle('QWidget Bg Color Experiment')
self.show()
if __name__ == '__main__':
APP = QApplication(sys.argv)
EXP = BgColorExperiment()
sys.exit(APP.exec_())
来源:https://stackoverflow.com/questions/46007891/setting-background-color-of-pyqt5-qwidget