Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

QColorButton: A color-selector tool for PyQt

Below is a short snippet to implement a Color-picker attached to a button in Qt. Clicking on the button pops up a dialog (native) to select a color. The color is shown by the color of the button face. A right-click option is included to allow clearing of the color setting (returning the value to None).

The below snippet is written for PyQt5, but changing it to PySide should require no more than altering the pyqtSignal call.

class QColorButton(QPushButton):
    Custom Qt Widget to show a chosen color.

    Left-clicking the button shows the color-chooser, while
    right-clicking resets the color to None (no-color).    

    colorChanged = pyqtSignal()

    def __init__(self, *args, **kwargs):
        super(QColorButton, self).__init__(*args, **kwargs)

        self._color = None

    def setColor(self, color):
        if color != self._color:
            self._color = color

        if self._color:
            self.setStyleSheet("background-color: %s;" % self._color)

    def color(self):
        return self._color

    def onColorPicker(self):
        Show color-picker dialog to select color.

        Qt will use the native dialog by default.

        dlg = QColorDialog(self)
        if self._color:

        if dlg.exec_():

    def mousePressEvent(self, e):
        if e.button() == Qt.RightButton:

        return super(QColorButton, self).mousePressEvent(e)

This post first appeared on Martin Fitzpatrick – Python Coder, Postgraduate, please read the originial post: here

Share the post

QColorButton: A color-selector tool for PyQt


Subscribe to Martin Fitzpatrick – Python Coder, Postgraduate

Get updates delivered right to your inbox!

Thank you for your subscription