Skip to content

[PyQt5] Tutorial(11) Use QColorDialog to let user select color

Recently, when developing projects that I am interested in, there is a need to choose "colors". I wanted to build a simple color palette for the user to select the color, and then I was getting the color the user wanted.

This is not a hard mission, I have done it before. However, in the process of checking the information, I found that using the QColorDialog in PyQt5 is actually very convenient.

If you are interested in PyQt5, you can refer the official guide: https://www.riverbankcomputing.com/static/Docs/PyQt5/index.html?highlight=qicon

Not much nonsense, let's look at the code.


How to use QColorDialog

The method of use is very simple, let's look at the Sample Code:

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *


class colorSelector(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Color Selector')
        self.setGeometry(600, 500, 400, 200)

        # OpenColorDialog
        color = QColorDialog.getColor()
        if color.isValid():
            print(color.name())


if __name__ == '__main__':
    app = QApplication([])
    window = colorSelector()
    window.show()
    sys.exit(app.exec_())


Output:

The most important code is:

color = QColorDialog.getColor()


The code will display the default graphical interface above and return the color selected by the user.

For example, I chose blue:

Our program will return:

#0004ff

We often use the numerical value to represent the color. In addition to the classic RGB three-primary color numerical value, we also often use this Hex Color Code. Everyone who has written a web page must be familiar with it.

After we get the color selected by the user, we can start applying it in our own application! For example, in the program I want to write, the color selection is so that the user can change the color of the brush.

After we get the color selected by the user, we can start applying it in our own application! For example, in the program I want to write, the color selection is so that the user can change the color of the brush.

I hope everyone can choose the color smoothly.


Read More

Leave a Reply