目錄
PyQt5筆記(01) – 創建空白窗體
PyQt5筆記(02) – 按鈕點擊事件
PyQt5筆記(03) – 消息框
PyQt5筆記(04) – 文本框的使用
PyQt5筆記(05) – 絕對位置
爲了便於後期更新,所有目錄已彙總到一個鏈接,具體請移步到這裏
正文
本節主要介紹PyQt的調色板的使用,在點擊按鈕後對窗體進行着色,具體代碼如下
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QColorDialog
from PyQt5.QtGui import QPainter
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 color dialog'
self.left = 100
self.top = 100
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):
qp = QPainter(self)
color = QColorDialog.getColor()
if color.isValid():
# 實例化調色板
palette1 = QtGui.QPalette()
# 設置調色板顏色
palette1.setColor(palette1.Background, color)
# 應用調色板
self.setPalette(palette1)
print(color.name())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())