Congratulations to our 2022 Qt Champions!

Qt Style Sheets and Custom Painting Example

  • Hi,
    I'm trying to follow the c++ example of assigning a qproperty on a custom widget to be update via stylesheet in a paint event.

    I dont get any errors, but I also am not getting my stylesheet color. Is QtCore.Property the same as Q_PROPERTY in the example?

    I could only find futher readings on the QtCore.Property here:

    The expected behavior from the code below is to have to button change to Red (defined in stylesheet) when clicked.

    import sys
    import os
    from PySide2 import QtWidgets, QtGui, QtCore
    from PySide2.QtCore import Qt
    class CustomWidget(QtWidgets.QPushButton):
        def __init__(self, *args, **kwargs):
            super(CustomWidget, self).__init__(*args, **kwargs)
            self._shmee = None
        def get_shmee(self):
            return self._shmee
        def set_shmee(self, shmee):
            print(f'SET: {shmee}')
            self._shmee = shmee
        def paintEvent(self, event):
            painter = QtGui.QPainter(self)
            width_full = painter.device().width()
            height_full = painter.device().height()
            brush = QtGui.QBrush()
            if self.isChecked():
                brush.setColor(QtGui.QColor(10, 10, 250))
            rect = QtCore.QRect(0, 0, width_full, height_full)
            painter.fillRect(rect, brush)
        def mousePressEvent(self, event):
            self.setChecked(not self.isChecked())
        shmee = QtCore.Property(QtGui.QColor, get_shmee, set_shmee)
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        custom_style = CustomWidget()
        script_dir = os.path.dirname(__file__)
        stylesheet_path = 'style.css'
        with open(os.path.join(script_dir, stylesheet_path)) as sty:
        rec = app.exec_()

    style.css file :

    CustomWidget {
        qproperty-shmee: rgb(250, 10, 10);

  • Ha!
    ... I was missing a comma in my stylesheet :P

    qproperty-shmee: rgb(20, 100, 100);

Log in to reply