[파이썬] PyQt 컬러 선택 다이얼로그 (`QColorDialog`)

In PyQt, the QColorDialog is a built-in dialog that allows users to select colors. This dialog provides a user-friendly interface with a color wheel and various color selection tools.

QColorDialog

Prerequisites

Before getting started, make sure you have PyQt5 installed. You can install it using pip:

pip install pyqt5

Creating a QColorDialog

To create a QColorDialog, first, import the necessary classes from PyQt:

from PyQt5.QtWidgets import QApplication, QColorDialog

Next, create an instance of QApplication and then create a QColorDialog:

app = QApplication([])
color_dialog = QColorDialog()

Opening the Dialog

To open the color dialog, call the exec_() method on the QColorDialog instance:

color_dialog.exec_()

Retrieving the Selected Color

To retrieve the color selected by the user, you can use the currentColor() method:

color = color_dialog.currentColor()

The currentColor() method returns a QColor object, which can be used to get the RGB or HSV values of the selected color.

Example

Here’s a complete example of using the QColorDialog:

from PyQt5.QtWidgets import QApplication, QColorDialog

app = QApplication([])

color_dialog = QColorDialog()
color_dialog.exec_()

color = color_dialog.currentColor()
selected_rgb = color.getRgb()
selected_hsv = color.getHsv()

print("Selected Color (RGB):", selected_rgb)
print("Selected Color (HSV):", selected_hsv)

In this example, the selected color is printed as both RGB and HSV values. You can modify this example to integrate the color dialog into your own PyQt application.

That’s it! You now know how to use the QColorDialog in PyQt to allow users to select colors easily.