QColorDialog

QColorDialog is a dialog where you can select the color. ( QColorDialog official document )


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFrame, QColorDialog
from PyQt5.QtGui import QColor


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        col = QColor(0, 0, 0)

        self.btn = QPushButton('Dialog', self)
        self.btn.move(30, 30)
        self.btn.clicked.connect(self.showDialog)

        self.frm = QFrame(self)
        self.frm.setStyleSheet('QWidget { background-color: %s }' % col.name())
        self.frm.setGeometry(130, 35, 100, 100)

        self.setWindowTitle('Color Dialog')
        self.setGeometry(300, 300, 250, 180)
        self.show()

    def showDialog(self):

        col = QColorDialog.getColor()

        if col.isValid():
            self.frm.setStyleSheet('QWidget { background-color: %s }' % col.name())


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

First, create a push button and a QFrame, and set the background color of the QFrame widget to black.

Use QColorDialog to change the background color.


Description

col = QColor(0, 0, 0)

Use QColor to make black for background color.


col = QColorDialog.getColor()

Pop up QColorDialog, and use getColor() method to save the color.


if col.isValid():
 self.frm.setStyleSheet('QWidget { background-color: %s }' % col.name())

If you select the color and press the ‘OK’ button, the Boolean value of col.isValid() becomes True; if you press the ‘Cancel’ button, the Boolean value becomes False.

The selected color is set as the background color of the frame.


Results

../_images/5_2_qcolordialog.png ../_images/5_2_qcolordialog_mac.png

Figure 6-2. Color dialog.


Prev/Next