from PySide6.QtWidgets import QApplication, QPushButton, QMainWindow from PySide6.QtGui import QPainter, QRadialGradient, QColor, QFont from PySide6.QtCore import Qt, QRectF, QPropertyAnimation, QEasingCurve import sys class GradientButton(QPushButton): def __init__(self, text, parent=None): super().__init__(text, parent) self.setFlat(True) self.setFont(QFont("Arial", 14, QFont.Bold)) self.setMouseTracking(True) self.hover = False self.animation = QPropertyAnimation(self, b"geometry") self.animation.setDuration(100) self.animation.setEasingCurve(QEasingCurve.OutQuad) def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) rect = self.rect() gradient = QRadialGradient(rect.width()/2,rect.top(), rect.width()) gradient.setColorAt(0, QColor(0, 0, 0)) gradient.setColorAt(1, QColor(255, 255, 255)) if self.hover: gradient.setColorAt(0, QColor(30, 30, 30)) gradient.setColorAt(1, QColor(220, 220, 220)) brush = gradient painter.setBrush(brush) painter.setPen(Qt.NoPen) radius = 10 painter.drawRoundedRect(QRectF(rect), radius, radius) painter.setPen(QColor(0, 0, 0) if not self.hover else QColor(50, 50, 50)) painter.drawText(rect, Qt.AlignCenter, self.text()) def enterEvent(self, event): self.hover = True self.update() super().enterEvent(event) def leaveEvent(self, event): self.hover = False self.update() super().leaveEvent(event) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: # 开始缩放动画(缩小) geom = self.geometry() new_geom = geom.adjusted(5, 5, -5, -5) self.animation.stop() self.animation.setStartValue(geom) self.animation.setEndValue(new_geom) self.animation.start() super().mousePressEvent(event) def mouseReleaseEvent(self, event): if event.button() == Qt.LeftButton: # 恢复原始大小 geom = self.geometry() new_geom = geom.adjusted(-5, -5, 5, 5) self.animation.stop() self.animation.setStartValue(geom) self.animation.setEndValue(new_geom) self.animation.start() super().mouseReleaseEvent(event) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("带动画的渐变按钮示例") self.setFixedSize(400, 300) self.button = GradientButton("点击我", self) self.button.setGeometry(150, 130, 100, 40) self.button.clicked.connect(self.on_button_click) def on_button_click(self): print("按钮被点击了!") if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())