首页 > 解决方案 > 如何使用样式表设置 qwidget 的背景颜色?

问题描述

Qt 样式表有一些我似乎不明白的地方。我只想将小部件的背景颜色设置为白色。但由于某种原因,背景颜色实际上只出现在我的小部件的孩子中。

我试图添加self.setAutoFillBackground(True)到我的代码中,但没有成功。

我还尝试从https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget调色解决方案。它有效,但前提是我没有设置底部边框所需的样式表。

class TopLabelNewProject(qt.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        layout = qt.QHBoxLayout(self)
        layout.setContentsMargins(40, 0, 32, 0)
        self.setLayout(layout)
        self.setFixedHeight(80)
        self.setStyleSheet("""
            background-color: white;
            border-bottom: 1px solid %s;
            """ % colors.gray)

        self.label = qt.QLabel("Dashboard")
        self.label.setStyleSheet("""
            QLabel {
                font: medium Ubuntu;
                font-size: 20px;
                color: %s;
            }""" % colors.gray_dark)
        layout.addWidget(self.label, alignment=qt.Qt.AlignLeft)

        self.newProjectButton = Buttons.DefaultButton("New project", self)
        layout.addWidget(self.newProjectButton, alignment=qt.Qt.AlignRight)

注意:Buttons.DefaultButton 只是一个带有自定义样式表的 QPushButton。

这就是我想要实现的,带有标签和按钮的白色标题栏: 我想要的是

但只有标签有白色背景。

我得到了什么

标签: pythonpyqtpyqt5qtstylesheets

解决方案


试试看:

import sys
from PyQt5 import Qt as qt 

class TopLabelNewProject(qt.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        layout = qt.QHBoxLayout(self)
        layout.setContentsMargins(40, 0, 32, 0)
        self.setLayout(layout)
        self.setFixedHeight(80)

        self.label = qt.QLabel("Dashboard")

        layout.addWidget(self.label, alignment=qt.Qt.AlignLeft)

#        self.newProjectButton = Buttons.DefaultButton("New project", self)
        self.newProjectButton = qt.QPushButton("New project", self)
        layout.addWidget(self.newProjectButton, alignment=qt.Qt.AlignRight)


style = '''
QWidget {
    background-color: white;
} 

QLabel {
    font: medium Ubuntu;
    font-size: 20px;
    color: #006325;     
}        

QPushButton {
    background-color: #006325;
    color: white;

    min-width:  70px;
    max-width:  70px;
    min-height: 70px;
    max-height: 70px;

    border-radius: 35px;        
    border-width: 1px;
    border-color: #ae32a0;
    border-style: solid;
}
QPushButton:hover {
    background-color: #328930;
}
QPushButton:pressed {
    background-color: #80c342;
}    

'''


if __name__ == '__main__':
    app = qt.QApplication(sys.argv)

    app.setStyleSheet(style)

    ex = TopLabelNewProject()
    ex.show()
    sys.exit(app.exec_())  

在此处输入图像描述


推荐阅读