To give a custom QWidget a stylesheet pseudo-state, you can follow these steps:
Define a custom QWidget class that inherits from QWidget.
In the constructor of the custom class, set the object name to a unique identifier. For example:
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self.setObjectName("my-widget")
my-widget:pressed {
background-color: red;
}
setStyleSheet()
method. For example:my_widget = MyWidget()
my_widget.setStyleSheet("MyWidget:pressed { background-color: red; }")
setProperty()
method to set the widget's state to the desired pseudo-state. For example:my_widget.setProperty("pressed", True)
my_widget.setStyleSheet("MyWidget:pressed { background-color: red; }")
my_widget.style().unpolish(my_widget)
my_widget.style().polish(my_widget)
Note that after setting the widget's property to the desired pseudo-state, you need to force the widget to reapply the stylesheet by calling unpolish()
and polish()
.
Asked: 2022-12-17 11:00:00 +0000
Seen: 10 times
Last updated: Apr 23 '21