Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom widget background color in pyside2

Tags:

python

qt

pyside2

Trying to work out how to set the background color in a QWidget. Here is my code:

class ParentTester(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        left = ColorTester(self)
        right = QFrame(self)
        right.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        layout = QHBoxLayout()
        layout.addWidget(left)
        layout.addWidget(right)
        self.setLayout(layout)


class ColorTester(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(128, 0, 0))
        self.setPalette(palette)

def main():
    import sys
    from PySide2.QtWidgets import QApplication

    app = QApplication([])

    works = True

    if works:
        win = ColorTester()
    else:
        win = ParentTester()
    win.show()
    win.resize(640, 480)

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

This works if I create the class as a topmost window. However if I make it a child of another control, the background color goes back to the default. Some of the other color roles do take effect, but not the background color. Not only that, but the colors get passed through to child controls.

How can I change the background color of a control but not its child controls?

like image 430
fuzzboil Avatar asked Oct 20 '25 09:10

fuzzboil


1 Answers

By default, the child widgets take the color of the window, so you observe that effect, if you want the custom background color to be used then you must enable the autoFillBackground property:

class ColorTester(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(128, 0, 0))
        self.setPalette(palette)
        self.setAutoFillBackground(True)

enter image description here

like image 110
eyllanesc Avatar answered Oct 21 '25 21:10

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!