Setting background color of PyQt5 QWidget

坚强是说给别人听的谎言 提交于 2020-01-25 21:16:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!