Set background colour for a custom QWidget

2024/9/24 15:21:15

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

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.

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.

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
}

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

Answer

The simplest fix is this:

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

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:

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

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, QtWidgetsclass 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:

screenshot

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).

https://en.xdnf.cn/q/71688.html

Related Q&A

Plotly: How to set up a color palette for a figure created with multiple traces?

I using code below to generate chart with multiple traces. However the only way that i know to apply different colours for each trace is using a randon function that ger a numerico RGB for color. But r…

Which implementation of OrderedDict should be used in python2.6?

As some of you may know in python2.7/3.2 well get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompati…

Signal Handling in Windows

In Windows I am trying to create a python process that waits for SIGINT signal.And when it receives SIGINT I want it to just print a message and wait for another occurrence of SIGINT.So I used signal h…

Python tkinter.filedialog askfolder interfering with clr

Im mainly working in Spyder, building scripts that required a pop-up folder or file Browse window.The code below works perfect in spyder. In Pycharm, the askopenfilename working well, while askdirector…

Run a function for each element in two lists in Pandas Dataframe Columns

df: col1 [aa, bb, cc, dd] [this, is, a, list, 2] [this, list, 3]col2 [[ee, ff, gg, hh], [qq, ww, ee, rr]] [[list, a, not, 1], [not, is, this, 2]] [[this, is, list, not], [a, not, list, 2]]What Im tryin…

cannot filter palette images error when doing a ImageEnhance.Sharpness()

I have a GIF image file. I opened it using PIL.Image and did a couple of size transforms on it. Then I tried to use ImageSharpness.Enhance() on it...sharpener = PIL.ImageEnhance.Sharpness(img) sharpene…

Is there a PyPi source download link that always points to the lastest version?

Say my latest version of a package is on PyPi and the source can be downloaded with this url:https://pypi.python.org/packages/source/p/pydy/pydy-0.3.1.tar.gzId really like to have a url that looks like…

Can this breadth-first search be made faster?

I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. Im d…

How to remove rows of a DataFrame based off of data from another DataFrame?

Im new to pandas and Im trying to figure this scenario out: I have a sample DataFrame with two products. df = Product_Num Date Description Price 10 1-1-18 Fruit Snacks 2.9910 1-2-18 …

Amazon S3 Python S3Boto 403 Forbidden When Signature Has + sign

I am using Django and S3Boto and whenever a signature has a + sign in it, I get a 403 Forbidden. If there is no + sign in the signature, I get the resource just fine. What could be wrong here?UPDATE: …