QColorDialog provides a dialog widget for selecting colour values.
代码:
# coding='utf-8'
from PyQt5.QtWidgets import QWidget, QApplication,\
QColorDialog, QFrame, QPushButton
from PyQt5.QtGui import QColor
import sys
class Gui(QWidget):
def __init__(self):
super().__init__()
self.start()
def start(self):
# Qt的颜色构造函数:
"""
QColor(Qt.GlobalColor)
QColor(int)
QColor(QRgba64)
QColor(Any)
QColor()
QColor(int, int, int, alpha: int = 255)
QColor(str)
QColor(Union[QColor, Qt.GlobalColor, QGradient])
"""
# 初始是黑色
color = QColor(0, 0, 0)
self.button = QPushButton('Dialog', self)
self.button.move(20, 20)
self.button.clicked.connect(self.show_dialog)
# QtFrame构造函数:\
# QFrame(parent: QWidget = None,\
# flags: Union[Qt.WindowFlags, Qt.WindowType]\
# = Qt.WindowFlags())
self.frame = QFrame(self)
# 'QWidget {background-color: %s}' % color.name()\
# 这是一种特定格式的字符串,作用是设置颜色\
# color.name() --> 返回值是 # 000000这样的
self.frame.setStyleSheet(
'QWidget {background-color: %s}' % color.name())
self.frame.setGeometry(130, 22, 100, 100)
self.setGeometry(300, 300, 250, 180)
self.setWindowTitle('颜色选择对话框')
self.show()
def show_dialog(self):
# 弹出颜色选择对话框, 返回值是QColor
col = QColorDialog.getColor()
# 检测用的选择是否合法(点击cancel就是非法,否则就是合法)
if col.isValid():
# 同前面一样,设置frame框架的颜色
self.frame.setStyleSheet(
'QWidget {background-color: %s}'
% col.name())
app = QApplication(sys.argv)
gui = Gui()
sys.exit(app.exec_())
运行结果:
image.png
image.png
image.png
网友评论