Work with QColorDialog in PyQt6

Recently, I was working on a PyQt6 project where I needed to let users select colors for various UI elements. The solution? QColorDialog is a useful dialog that makes color selection intuitive and customizable.

In this article, I will share how to implement color pickers in your PyQt6 applications using QColorDialog. I’ll cover everything from basic usage to advanced customization options that will make your app more user-friendly.

So let us get started..

QColorDialog in PyQt6

QColorDialog is a pre-built dialog class in PyQt6 that allows users to select colors. Think of it as a specialized window when you need the user to choose a color for something in your application.

This dialog comes with a variety of features:

  • Standard and custom color selection
  • RGB, HSV, and hex color code support
  • Alpha channel (transparency) settings
  • Recently used colors section

Basic Usage of QColorDialog

The simplest way to use QColorDialog is to call its static method getColor()in Python. This displays a standard color dialog and returns the selected color.

Here’s a basic example:

import sys
from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow, QColorDialog
from PyQt6.QtGui import QColor

class ColorPickerDemo(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Color Picker Demo")
        self.setGeometry(100, 100, 400, 200)

        # Create a button to open the color dialog
        self.button = QPushButton("Select Color", self)
        self.button.setGeometry(150, 80, 100, 30)
        self.button.clicked.connect(self.open_color_dialog)

        # Default background color
        self.current_color = QColor(255, 255, 255)
        self.setStyleSheet(f"background-color: {self.current_color.name()}")

    def open_color_dialog(self):
        color = QColorDialog.getColor(self.current_color, self, "Choose Background Color")

        # Check if a valid color was selected (not canceled)
        if color.isValid():
            self.current_color = color
            self.setStyleSheet(f"background-color: {color.name()}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ColorPickerDemo()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

QColorDialog in PyQt6

In this example, clicking the button opens a color dialog. When the user selects a color and clicks OK, the application’s background changes to that color.

Use QColorDialog with Alpha Channel

Sometimes you need to allow users to select colors with transparency. The alpha channel represents opacity, where 0 is completely transparent and 255 is fully opaque.

Here’s how to enable alpha channel selection:

def open_color_dialog_with_alpha(self):
    # Set the options flag to show alpha channel
    options = QColorDialog.ColorDialogOption.ShowAlphaChannel

    # Get color with alpha channel enabled
    color = QColorDialog.getColor(self.current_color, self, "Choose Color with Transparency", options)

    if color.isValid():
        self.current_color = color
        # Use rgba to apply the transparency
        self.setStyleSheet(f"background-color: rgba({color.red()}, {color.green()}, {color.blue()}, {color.alpha()/255});")

I executed the above example code and added the screenshot below.

PyQt6 QColorDialog

Enabling the alpha channel in QColorDialog lets users choose transparent colors, adding flexibility and visual depth to your PyQt6 applications.

Create a Custom QColorDialog Instance

Instead of using the static method, you can create an instance of QColorDialog for more control:

def open_custom_color_dialog(self):
    dialog = QColorDialog(self.current_color, self)
    dialog.setWindowTitle("Custom Color Selection")
    dialog.setOption(QColorDialog.ColorDialogOption.ShowAlphaChannel, True)
    dialog.setOption(QColorDialog.ColorDialogOption.DontUseNativeDialog, True)

    # Connect to currentColorChanged signal to preview colors
    dialog.currentColorChanged.connect(self.preview_color)

    if dialog.exec() == QColorDialog.DialogCode.Accepted:
        self.current_color = dialog.currentColor()
        self.apply_color(self.current_color)
    else:
        # Revert to original color if canceled
        self.apply_color(self.current_color)

def preview_color(self, color):
    # Temporarily show the selected color
    self.apply_color(color)

def apply_color(self, color):
    self.setStyleSheet(f"background-color: rgba({color.red()}, {color.green()}, {color.blue()}, {color.alpha()/255});")

I executed the above example code and added the screenshot below.

Work with QColorDialog in PyQt6

Creating a custom QColorDialog instance gives you greater control over the dialog’s behavior, enabling features like live color preview and transparency support in PyQt6.

Read Use QListWidget in PyQt6

Use Custom Colors in QColorDialog

Python QColorDialog allows you to set custom colors that users can easily access:

def set_custom_colors(self):
    dialog = QColorDialog(self)

    # Define custom colors (these are just examples)
    custom_colors = [
        QColor(255, 0, 0),      # Red
        QColor(0, 255, 0),      # Green
        QColor(0, 0, 255),      # Blue
        QColor(255, 255, 0),    # Yellow
        QColor(0, 255, 255),    # Cyan
        QColor(255, 0, 255),    # Magenta
        QColor(128, 0, 0),      # Dark Red
        QColor(0, 128, 0),      # Dark Green
        QColor(0, 0, 128),      # Dark Blue
        QColor(128, 128, 0),    # Olive
        QColor(128, 0, 128),    # Purple
        QColor(0, 128, 128),    # Teal
        QColor(192, 192, 192),  # Silver
        QColor(128, 128, 128),  # Gray
        QColor(64, 64, 64),     # Dark Gray
        QColor(255, 128, 0)     # Orange
    ]

    # Set custom colors
    for i, color in enumerate(custom_colors):
        dialog.setCustomColor(i, color.rgb())

    if dialog.exec() == QColorDialog.DialogCode.Accepted:
        self.current_color = dialog.currentColor()
        self.apply_color(self.current_color)

Using custom colors in QColorDialog allows you to provide a predefined palette, giving users quick access to brand or theme-specific colors in your PyQt6 application.

Practical Application: A Text Editor with Color Options

Here’s a more complete example of how you might use QColorDialog in a real application, a simple text editor that lets users change text and background colors:

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QTextEdit, QToolBar, 
                           QColorDialog, QAction)
from PyQt6.QtGui import QColor, QIcon, QTextCharFormat
from PyQt6.QtCore import Qt

class SimpleTextEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Text Editor with Color Options")
        self.setGeometry(100, 100, 800, 600)

        # Create text edit widget
        self.text_edit = QTextEdit()
        self.setCentralWidget(self.text_edit)

        # Set default text and font size
        self.text_edit.setPlainText("Select some text and use the color buttons to change its appearance.")
        self.text_edit.setFontPointSize(12)

        # Create toolbar
        self.create_toolbar()

    def create_toolbar(self):
        toolbar = QToolBar("Formatting")
        self.addToolBar(toolbar)

        # Text color action
        text_color_action = QAction("Text Color", self)
        text_color_action.triggered.connect(self.change_text_color)
        toolbar.addAction(text_color_action)

        # Background color action
        highlight_action = QAction("Highlight Color", self)
        highlight_action.triggered.connect(self.change_highlight_color)
        toolbar.addAction(highlight_action)

        # Editor background color
        editor_bg_action = QAction("Editor Background", self)
        editor_bg_action.triggered.connect(self.change_editor_background)
        toolbar.addAction(editor_bg_action)

    def change_text_color(self):
        # Get current format to use as initial color
        cursor = self.text_edit.textCursor()
        current_format = cursor.charFormat()
        current_color = current_format.foreground().color()

        # Open color dialog
        color = QColorDialog.getColor(current_color, self, "Select Text Color")

        if color.isValid():
            # Create new format with selected color
            format = QTextCharFormat()
            format.setForeground(color)

            # Apply to selected text
            cursor.mergeCharFormat(format)
            self.text_edit.mergeCurrentCharFormat(format)

    def change_highlight_color(self):
        cursor = self.text_edit.textCursor()
        current_format = cursor.charFormat()
        current_color = current_format.background().color()

        color = QColorDialog.getColor(current_color, self, "Select Highlight Color")

        if color.isValid():
            format = QTextCharFormat()
            format.setBackground(color)

            cursor.mergeCharFormat(format)
            self.text_edit.mergeCurrentCharFormat(format)

    def change_editor_background(self):
        current_color = self.text_edit.palette().color(self.text_edit.backgroundRole())

        color = QColorDialog.getColor(current_color, self, "Select Editor Background")

        if color.isValid():
            # Set the stylesheet for the text edit widget
            self.text_edit.setStyleSheet(f"background-color: {color.name()};")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SimpleTextEditor()
    window.show()
    sys.exit(app.exec())

Tips for Improving User Experience with PyQt6 QColorDialog

  1. Provide an Initial Color: Always pass the current color to QColorDialog to provide context to the user.
  2. Use Descriptive Titles: Set clear titles for your dialog so users know what they’re choosing a color for.
  3. Consider Preview Functionality: Connect to the currentColorChanged signal to provide real-time previews of color selections.
  4. Remember User Selections: Store previously selected colors in your application settings to provide continuity between sessions.
  5. Add Custom Colors: For domain-specific applications, pre-define colors that make sense for your users.

QColorDialog is an efficient component in PyQt6 that can significantly enhance the user experience in applications where color selection is important. From basic color picking to advanced features like transparency and custom color palettes, it provides all the tools needed to create intuitive color selection interfaces.

I hope you found this guide helpful for implementing color selection in your PyQt6 applications.

PyQt6-related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.