Search code examples
pythonpython-3.xpyqtpyqt4

Change the style and background color of Widget Window in Python


enter image description here

def color_picker(self):
    color = QtGui.QColorDialog.getColor()
    self.setStyleSheet("QWidget { background-color: %s}" % color.name())
    global selectedcolor
    selectedcolor=color.name()
    print(selectedcolor)
    global RGBcolorfromcolorpicker
    RGBcolorfromcolorpicker=selectedcolor.lstrip('#')

    #This line doesn't work.
    self.QColorDialog.setStyleSheet('QTabBar::tab{background-color: red;}')

    self.send_rgb_color()

Solution

  • Instead of just using a static method you can use an object of the class, in this case I have created a class that already implements the functionality of changing the color:

    from PyQt4 import QtCore, QtGui
    
    class ColorDialog(QtGui.QColorDialog):
        def __init__(self, initial=QtGui.QColor(), parent=None):
            super(ColorDialog, self).__init__(parent)
            self.setOption(QtGui.QColorDialog.DontUseNativeDialog)
            self.currentColorChanged.connect(self.onCurrentColorChanged)
            self.onCurrentColorChanged(self.currentColor())
    
        @QtCore.pyqtSlot(QtGui.QColor)
        def onCurrentColorChanged(self, color):
            self.setStyleSheet("QColorDialog { background-color: %s}" % color.name())
    
    if __name__ == '__main__':
        import sys
        app = QtGui.QApplication(sys.argv)
        w = ColorDialog()
        if w.exec_() == QtGui.QDialog.Accepted:
            print(w.currentColor())