示例效果如下:
示例代码:
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 4 """ 5 ZetCode PyQt5 tutorial 6 7 In this example, we select a color value 8 from the QColorDialog and change the background 9 color of a QFrame widget. 10 11 Author: Jan Bodnar 12 Website: zetcode.com 13 Last edited: August 2017 14 """ 15 16 from PyQt5.QtWidgets import (QWidget, QPushButton, QFrame, QColorDialog, QApplication) 17 from PyQt5.QtGui import QColor 18 import sys 19 20 21 class Example(QWidget): 22 23 def __init__(self): 24 super().__init__() 25 26 self.initUI() 27 28 def initUI(self): 29 30 # 初始化QFrame的颜色为黑色 31 col = QColor(0, 0, 0) 32 33 self.btn = QPushButton('Dialog', self) 34 self.btn.move(20, 20) 35 36 self.btn.clicked.connect(self.showDialog) 37 38 self.frm = QFrame(self) 39 self.frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) 40 print(col.name()) 41 self.frm.setGeometry(130, 22, 100, 100) 42 43 self.setGeometry(300, 300, 250, 180) 44 self.setWindowTitle('Color dialog') 45 self.show() 46 47 def showDialog(self): 48 49 # 弹出QColorDialog 50 col = QColorDialog.getColor() 51 52 # 我们要先检查col的值。 53 # 如果点击的是Cancel按钮,返回的颜色值是无效的。 54 # 当颜色值有效时,我们通过样式表(style sheet)来改变背景颜色 55 if col.isValid(): 56 self.frm.setStyleSheet("QWidget { background-color: %s }" 57 % col.name()) 58 59 60 if __name__ == '__main__': 61 62 app = QApplication(sys.argv) 63 ex = Example() 64 sys.exit(app.exec_())