How can I run a QColorDialog window while running QMainWindow?

518 views Asked by At

Using PyQt5, I'd like to use the QColorDialog widget to get a color, but keep the QMainWindow running so that any changes to the color are instantly updated in the main GUI. The user would not have to press "OK" to send the new color to the main GUI -- it would update constantly to match whatever color is currently in the subwindow. Is this possible using QColorDialog?

1

There are 1 answers

0
eyllanesc On

You can only get the color that is clicked on the palette if you use the QColorDialog of Qt and not the native of each OS so you must set the options with QColorDialog::DontUseNativeDialog:

from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        button = QtWidgets.QPushButton("Open QColorDialog")
        self.label = QtWidgets.QLabel("Background", alignment=QtCore.Qt.AlignCenter)
        self.label.setAutoFillBackground(True)
        lay = QtWidgets.QVBoxLayout(central_widget)
        lay.addWidget(button)
        lay.addWidget(self.label)

        self.color_dialog = QtWidgets.QColorDialog(self)
        self.color_dialog.setOptions(QtWidgets.QColorDialog.DontUseNativeDialog |
                                     QtWidgets.QColorDialog.NoButtons)
        self.color_dialog.currentColorChanged.connect(self.on_currentColorChanged)
        button.clicked.connect(self.color_dialog.show)

    @QtCore.pyqtSlot(QtGui.QColor)
    def on_currentColorChanged(self, color):
        pal = self.label.palette()
        pal.setColor(QtGui.QPalette.Background, color)
        self.label.setPalette(pal)
        # or
        # self.label.setStyleSheet("background-color: {}".format(color.name()))

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())