Home ยป PyQt5 QColorDialog widget

PyQt5 QColorDialog widget

In this article we look at the QColorDialog

It is a dialog box of a color picker widget. A color picker is a graphical user interface widget, these are commonly found in graphics software, they are used to select colors and sometimes to create color schemes.

It is popup type widget in PyQt5

The basic use case is to allow the user to choose the color this widget is useful in creating applications like paint.

Example

This is a basic example

You click on a button and the color dialog box appears, you can then select a color and it will be displayed in a label

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):

        color = 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 }' % color.name())
        self.frm.setGeometry(130, 35, 100, 100)

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

    def showDialog(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.frm.setStyleSheet('QWidget { background-color: %s }' % color.name())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Running this will show you something like this

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More