简体   繁体   中英

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.

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_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM