新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
pyqt實(shí)現(xiàn)按鈕呼吸背景
簡介
呼吸背景效果是一種常見的UI設(shè)計(jì)元素,它可以使按鈕在鼠標(biāo)懸停時(shí)產(chǎn)生漸變顏色的效果,給人一種視覺上的呼吸感,在PyQt中,我們可以通過重寫QWidget的paintEvent方法來實(shí)現(xiàn)這種效果。

創(chuàng)新互聯(lián)公司長期為成百上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為平順企業(yè)提供專業(yè)的網(wǎng)站制作、成都網(wǎng)站制作,平順網(wǎng)站改版等技術(shù)服務(wù)。擁有十年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
實(shí)現(xiàn)步驟
1、導(dǎo)入所需庫
2、創(chuàng)建自定義按鈕類
3、重寫paintEvent方法
4、設(shè)置按鈕屬性
5、測(cè)試呼吸背景效果
詳細(xì)代碼
導(dǎo)入所需庫
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import Qt, QTimer, QRect
from PyQt5.QtGui import QPainter, QBrush, QColor
import sys
class BreathingButton(QPushButton):
def __init__(self, parent=None):
super(BreathingButton, self).__init__(parent)
self._timer = QTimer(self)
self._timer.setInterval(100)
self._timer.timeout.connect(self.update)
self._timer.start()
self._color1 = QColor(255, 0, 0)
self._color2 = QColor(0, 255, 0)
self._color3 = QColor(0, 0, 255)
self._color4 = QColor(255, 255, 255)
self._current_color = self._color1
self._brush = QBrush(self._current_color)
self.setGeometry(100, 100, 200, 60)
self.setText("點(diǎn)擊我")
self.setStyleSheet("backgroundcolor: transparent;")
self.show()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(self._brush)
painter.drawRect(event.rect())
if self.isEnabled():
if self.hasFocus():
if self._current_color == self._color1:
self._current_color = self._color2
else:
self._current_color = self._color1
elif self._current_color == self._color1:
self._current_color = self._color4
else:
self._current_color = self._color3
painter.setBrush(QBrush(self._current_color))
painter.drawRect(event.rect())
painter.end()
super(BreathingButton, self).paintEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
button = BreathingButton()
sys.exit(app.exec_())
單元表格
| 序號(hào) | 方法/屬性 | 說明 |
| 1 | __init__ | 初始化自定義按鈕,設(shè)置定時(shí)器和顏色 |
| 2 | paintEvent | 重寫繪制事件,實(shí)現(xiàn)呼吸背景效果 |
| 3 | setGeometry | 設(shè)置按鈕位置和大小 |
| 4 | setText | 設(shè)置按鈕文本 |
| 5 | setStyleSheet | 設(shè)置按鈕樣式,使其透明 |
網(wǎng)站欄目:pyqt實(shí)現(xiàn)按鈕呼吸背景
轉(zhuǎn)載注明:http://www.dlmjj.cn/article/djgosog.html


咨詢
建站咨詢
