pyqt5實現按鈕新增背景圖片以及背景圖片的切換
阿新 • • 發佈:2018-11-11
簡介
對與控制元件QPushButton中的可以使用setStyleSheet設定它背景圖片。具體設定背景圖片的方法有兩種
self.button.setStyleSheet("QPushButton{background-image: url(img/1.png)}")
然而對於這種方法背景圖片無法進行邊框的自適應,可以使用下面的方法
self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}")
可以做到自適應邊框。
程式碼
程式碼裡面有兩個圖片需要使用,我放在下面了
程式碼1
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Example(QWidget): def __init__(self): super().__init__() self.initUI() # 介面繪製交給InitUi方法 def initUI(self): # 設定視窗的位置和大小 self.setGeometry(300, 300, 300, 220) # 設定視窗的標題 self.setWindowTitle('QPushButton') #控制元件QPushButton的定義和設定 self.button = QPushButton(self) self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}" "QPushButton:hover{border-image: url(img/1_1.png)}" "QPushButton:pressed{border-image: url(img/1_1.png)}") #設定控制元件QPushButton的位置和大小 self.button.setGeometry(100, 100, 50, 50) if __name__ == '__main__': # 建立應用程式和物件 app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_())
具體實現了按鈕背景圖片,以及滑鼠劃過按鈕的背景切換,以及按下按鈕的背景切換。
然而在按下按鈕,我需要直接進行圖片切換,且不回到原來的背景上。可以參考我的程式碼2。
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Example(QWidget): def __init__(self): super().__init__() self.initUI() # 介面繪製交給InitUi方法 self.slot_init() def initUI(self): # 設定視窗的位置和大小 self.setGeometry(300, 300, 300, 220) # 設定視窗的標題 self.setWindowTitle('QPushButton') #控制元件QPushButton的定義和設定 self.button = QPushButton(self) self.button.setStyleSheet("QPushButton{border-image: url(img/1.png)}" "QPushButton:hover{border-image: url(img/1_1.png)}") # 設定控制元件QPushButton的位置和大小 self.button.setGeometry(100, 100, 50, 50) def slot_init(self): self.button.clicked.connect(self.button_change) def button_change(self): # 切換圖示變亮 self.button.setStyleSheet('QPushButton{border-image:url(img/1_1.png)}') if __name__ == '__main__': # 建立應用程式和物件 app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_())
如果需要來回的切換,可以定義一個計數器來解決這個問題