PyQT5 顏色對話方塊

PyQt5 支援一種名為 QColorDialog 的顏色選擇器。此對話方塊是你在繪畫或圖形程式中看到的典型對話方塊。

要從 PyQt5 對話方塊中獲取顏色,只需呼叫:

color = QColorDialog.getColor()

![PyQt5 顏色對話方塊](/img/Tutorial/PyQt5/PyQt5 QColorDialog.png)

PyQt5 顏色對話方塊示例

下面的示例在單擊按鈕後開啟 QColorDialog,並返回所選顏色。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QColorDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QColor

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 color dialog - tastones.com'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('Open color dialog', self)
        button.setToolTip('Opens color dialog')
        button.move(10,10)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        openColorDialog(self)


def openColorDialog(self):
    color = QColorDialog.getColor()

    if color.isValid():
        print(color.name())

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