为自定义 QWidget 设置背景颜色 [英] Set background colour for a custom QWidget

查看:150
本文介绍了为自定义 QWidget 设置背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义 QWidget(来自 PyQt5),其背景颜色可以改变.但是,所有设置背景颜色的标准方法似乎都不适用于自定义 QWidget 类

I am attempting to create a custom QWidget (from PyQt5) whose background colour can change. However, all the standard methods of setting the background colour do not seem to work for a custom QWidget class

到目前为止,我已经尝试通过 QSS 样式表和设置调色板来更改颜色.这适用于常规 QWidget 但由于某种原因不适用于自定义小部件.

So far I have attempted to change the colour through QSS stylesheet and by setting the palette. This works for a regular QWidget but for some reason not a custom widget.

我在 C++ 文档中找到了需要 PaintEvent() 函数的参考自定义 QWidgets https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget 并且确实在 Python 中找到了对它的引用.但是,由于 PyQt5 中似乎不存在 QStyleOption,因此实现链接的paintevent 失败.

I have found reference custom QWidgets requiring a paintEvent() function in the C++ documentation https://wiki.qt.io/How_to_Change_the_Background_Color_of_QWidget and an did find one reference to it in Python. However, implementing the linked paintevent fails because QStyleOption does not seem to exist in PyQt5.

下面展示了我创建的 QWidget 类的高层次(它也包含一堆标签)和我用于 Widget 的 QSS(样式已在父小部件中设置但已尝试直接设置)

Below shows a high level of the QWidget class I created (it also contains a bunch of labels) and the QSS I used for the Widget (style has been set in a parent widget but have tried setting it directly)

class AlarmWidget(QWidget):
    def __init__(self, alarm, parent=None):
        super(AlarmWidget, self).__init__(parent)
        self.setFixedHeight(200)
        self.setProperty("active", True)

        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), PyQt5.QtCore.Qt.red)
        self.setPalette(p)

AlarmWidget {
  background-color: red
}

总的来说,无论我做什么,它都不允许我为自定义 QWidget 设置背景颜色,因此非常感谢帮助

Overall, no matter what I do, it does not let me set the background colour for the custom QWidget so would really appreciate help

推荐答案

最简单的解决方法是:

class AlarmWidget(QWidget):
    def __init__(self, alarm, parent=None):
    ...
    self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
    self.setStyleSheet('background-color: red')

<小时>

每当将样式表应用于自定义小部件或其祖先小部件之一时,就会发生此问题.引用 QWidget.setPalette 文档:


This issue happens whenever a stylesheet is applied to a custom widget or to one of its ancestor widgets. To quote from the QWidget.setPalette documentation:

警告:请勿将此功能与 Qt 样式表.使用样式表时,可以自定义小部件的调色板使用颜色",背景颜色",选择颜色",选择背景颜色"和替代背景颜色".

Warning: Do not use this function in conjunction with Qt Style Sheets. When using style sheets, the palette of a widget can be customized using the "color", "background-color", "selection-color", "selection-background-color" and "alternate-background-color".

然而,这里没有提到的是,出于性能原因,自定义小部件默认禁用了样式表支持.因此,为了让您的示例正常工作,您必须 (1) 通过样式表设置背景颜色,以及 (2) 使用 WA_StyledBackground 小部件属性.

What this fails to mention, however, is that for performance reasons custom widgets have stylesheet support disabled by default. So to get your example to work properly, you must (1) set the background colour via a stylesheet, and (2) explicitly enable stylesheet support using the WA_StyledBackground widget attribute.

演示这一点的最小示例如下所示:

A minimal example that demonstrates this is shown below:

import sys
from PyQt5 import QtCore, QtWidgets

class AlarmWidget(QtWidgets.QWidget):
    def __init__(self, alarm, parent=None):
        super(AlarmWidget, self).__init__(parent)
        self.setFixedHeight(200)
#         self.setAutoFillBackground(True)
#         p = self.palette()
#         p.setColor(self.backgroundRole(), QtCore.Qt.red)
#         self.setPalette(p)
        self.setAttribute(QtCore.Qt.WA_StyledBackground, True)
        self.setStyleSheet('background-color: red')

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setStyleSheet('background-color: green')
        self.widget = AlarmWidget('')
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.widget)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setWindowTitle('BG Colour Test')
    window.setGeometry(600, 100, 300, 200)
    window.show()
    sys.exit(app.exec_())

这应该显示一个包含绿色边框的红色矩形的窗口,如下所示:

This should show a window containing a red rectangle with a green border, like this:

为了进一步测试,只在 AlarmWidget 类中设置调色板,而不在 Window 类中设置样式表.这应该显示一个没有绿色边框的红色矩形.最后,只在 both 类中设置样式表 - 但没有 setAttribute 行.这应该显示一个没有内部红色矩形的纯绿色矩形(即不再应用自定义小部件上的样式表).

To test things further, set only the palette in the AlarmWidget class, but without setting a stylesheet in the Window class. This should show a red rectangle with no green border. Finally, set only the stylesheet in both classes - but without the setAttribute line. This should show a plain green rectangle with no inner red rectangle (i.e. the stylesheet on the custom widget is no longer applied).

这篇关于为自定义 QWidget 设置背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆