from PySide6.QtWidgets import QApplication, QPushButton, QMainWindow from PySide6.QtGui import QPainter, QLinearGradient, QColor, QFont from PySide6.QtCore import Qt, QRectF 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 def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 获取按钮的矩形区域 rect = self.rect() # 创建线性渐变,从中心线向上下渐变 gradient = QLinearGradient(rect.center().x(), rect.top(), rect.center().x(), rect.bottom()) gradient.setColorAt(0, QColor(225,225,225)) gradient.setColorAt(0.5, QColor('#1A1F38')) gradient.setColorAt(1, QColor(225,225,225)) brush = gradient painter.setBrush(brush) painter.setPen(Qt.NoPen) # 绘制圆角矩形作为按钮背景 radius = 2 # 圆角半径 painter.drawRoundedRect(QRectF(rect), radius, radius) # 绘制按钮文本 painter.setPen(QColor('#E8E9EB')) # 设置字体为白色 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) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("中心线性渐变按钮示例") self.setFixedSize(400, 300) # 创建自定义渐变按钮 self.button = GradientButton("点击我", self) self.button.setGeometry(100, 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())