Search code examples
pythonpyside2qcolordialog

Color Picker and Visualizer with Pyside2


I'm having a problem with pyside2. I need to implement a color picker that, when I choose a color, visualize that color in a little square.

I've done the color picker like this:

color = QtWidgets.QColorDialog.getColor()

but I don't know how to make a square (it should be a label?) and to colour it with the selected color.


Solution

  • If you can use a QLabel, to change the background color QPalette is used:

    from PySide2 import QtWidgets, QtGui, QtCore
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, *args, **kwargs):
            QtWidgets.QWidget.__init__(self, *args, **kwargs)
            lay = QtWidgets.QVBoxLayout(self)
            button = QtWidgets.QPushButton("Select color")
            button.clicked.connect(self.on_clicked)
            self.label = QtWidgets.QLabel()
            self.label.setAutoFillBackground(True)
            self.label.setFixedSize(100, 100)
    
            lay.addWidget(button)
            lay.addWidget(self.label)
    
        def on_clicked(self):
            color = QtWidgets.QColorDialog.getColor()
            if color.isValid():
                palette = self.label.palette()
                palette.setColor(QtGui.QPalette.Background, color)
                self.label.setPalette(palette)
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())
    

    Or use Qt Style Sheet:

    from PySide2 import QtWidgets, QtGui, QtCore
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, *args, **kwargs):
            QtWidgets.QWidget.__init__(self, *args, **kwargs)
            lay = QtWidgets.QVBoxLayout(self)
            button = QtWidgets.QPushButton("Select color")
            button.clicked.connect(self.on_clicked)
            self.label = QtWidgets.QLabel()
            self.label.setFixedSize(100, 100)
    
            lay.addWidget(button)
            lay.addWidget(self.label)
    
        def on_clicked(self):
            color = QtWidgets.QColorDialog.getColor()
            if color.isValid():
                self.label.setStyleSheet("background-color: {}".format(color.name()))
    
    if __name__ == '__main__':
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())