呼吸背景效果是一种常见的UI设计元素,它可以使按钮在鼠标悬停时产生渐变颜色的效果,给人一种视觉上的呼吸感,在PyQt中,我们可以通过重写QWidget的paintEvent方法来实现这种效果。

创新互联公司长期为成百上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为平顺企业提供专业的网站制作、成都网站制作,平顺网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制开发。
1、导入所需库
2、创建自定义按钮类
3、重写paintEvent方法
4、设置按钮属性
5、测试呼吸背景效果
导入所需库
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("点击我")
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_())
| 序号 | 方法/属性 | 说明 |
| 1 | __init__ | 初始化自定义按钮,设置定时器和颜色 |
| 2 | paintEvent | 重写绘制事件,实现呼吸背景效果 |
| 3 | setGeometry | 设置按钮位置和大小 |
| 4 | setText | 设置按钮文本 |
| 5 | setStyleSheet | 设置按钮样式,使其透明 |