1 """ 2 QPushButton:切換按鈕就是QPsuhButton的一種特殊模式,他有兩種狀態:按下和未按下。我們在點擊的時候切換兩種狀態,有很多場景會用到這個功能 3 Author:dengyexun 4 DateTime:2018.11.20 5 """ 6 from PyQt5.QtWidgets import QWidget, QPushButton, QFrame, QApplication 7 from PyQt5.QtGui import QColor 8 import sys 9 10 class Example(QWidget): 11 def __init__(self): 12 super().__init__() 13 14 self.initGUI() 15 16 def initGUI(self): 17 # 功能區 18 self.col = QColor(0, 0, 0) # 顏色句柄 19 # 初始化pushButton 20 redb = QPushButton('Red', self) 21 redb.setCheckable(True) 22 redb.move(60, 60) 23 # 槽與信號連接.當redb被點擊時,傳入一個bool值給setColor的pressed參數 24 redb.clicked[bool].connect(self.setColor) 25 26 greenb = QPushButton('Green', self) 27 greenb.setCheckable(True) 28 greenb.move(60, 80) 29 greenb.clicked[bool].connect(self.setColor) 30 31 blueb = QPushButton('Blue', self) 32 blueb.setCheckable(True) 33 blueb.move(60, 100) 34 blueb.clicked[bool].connect(self.setColor) 35 36 # QFrame對象 37 self.square = QFrame(self) 38 self.square.setGeometry(110,110,200,200) 39 # 更改QWidget的樣式風格 40 self.square.setStyleSheet("QWidget {backgroud-color:%s}" % self.col.name()) 41 42 43 # Frame 44 self.setGeometry(300, 300, 300, 200) 45 self.setWindowTitle("toggle button") 46 self.show() 47 48 def setColor(self, pressed): 49 """ 50 自定義槽函數 51 :param pressed: 鼠標被按下的狀態 52 :return: 53 """ 54 # 得到切換按鈕的信息,哪一個信號被觸發了 55 source = self.sender() 56 # 當按下按鈕 57 if pressed: 58 val = 255 59 else: 60 val = 0 61 # 判斷這個信號的文本內容 62 if source.text() == 'Red': 63 self.col.setRed(val) 64 elif source.text() == 'Green': 65 self.col.setGreen(val) 66 else: 67 self.col.setBlue(val) 68 # 更改QFrame的樣式風格,設置背景為特定的顏色 69 color = self.col.name() # 樣式的背景色編碼 70 self.square.setStyleSheet("QFrame {background-color:%s}" % self.col.name()) 71 72 73 print('ok') 74 75 76 if __name__ == '__main__': 77 app = QApplication(sys.argv) 78 ex = Example() 79 sys.exit(app.exec_())
