Ask Your Question
2

How can a custom QWidget be given a stylesheet pseudo-state?

asked 2022-12-17 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-23 07:00:00 +0000

lalupa gravatar image

To give a custom QWidget a stylesheet pseudo-state, you can follow these steps:

  1. Define a custom QWidget class that inherits from QWidget.

  2. 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")
  1. Define the pseudo-state in a stylesheet using the object name with the desired state. For example:
my-widget:pressed {
    background-color: red;
}
  1. Apply the stylesheet to the custom widget using the setStyleSheet() method. For example:
my_widget = MyWidget()
my_widget.setStyleSheet("MyWidget:pressed { background-color: red; }")
  1. Use the 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().

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-17 11:00:00 +0000

Seen: 10 times

Last updated: Apr 23 '21