要在PyQt5中自定义绘制QPushButton,你需要创建一个新的类,该类继承自QPushButton,并重写其paintEvent方法
import sys from PyQt5.QtCore import Qt, QRectF from PyQt5.QtGui import QPainter, QColor, QFont from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton class CustomPushButton(QPushButton): def __init__(self, text="", parent=None): super().__init__(text, parent) def paintEvent(self, event): # 创建一个QPainter对象 painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) # 设置绘制按钮时的颜色和样式 if self.isDown(): painter.setBrush(QColor(100, 100, 100)) else: painter.setBrush(QColor(200, 200, 200)) # 绘制按钮的外观 painter.drawRoundedRect(self.rect(), 5, 5) # 设置文本颜色和字体 pen = painter.pen() pen.setColor(Qt.black) painter.setPen(pen) font = QFont("Arial", 12) painter.setFont(font) # 计算文本的位置 text_rect = QRectF(self.rect()) text_rect.setTop(text_rect.top() + (text_rect.height() - painter.fontMetrics().height()) / 2) # 绘制文本 painter.drawText(text_rect, Qt.AlignCenter, self.text()) class MainWindow(QWidget): def __init__(self): super().__init__() # 创建自定义按钮 custom_button = CustomPushButton("Custom Button") custom_button.clicked.connect(self.on_custom_button_clicked) # 创建默认按钮 default_button = QPushButton("Default Button") default_button.clicked.connect(self.on_default_button_clicked) # 将按钮添加到布局中 layout = QVBoxLayout() layout.addWidget(custom_button) layout.addWidget(default_button) self.setLayout(layout) def on_custom_button_clicked(self): print("Custom button clicked!") def on_default_button_clicked(self): print("Default button clicked!") if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
这个示例展示了如何创建一个自定义的QPushButton子类(CustomPushButton),并重写其paintEvent方法以自定义按钮的外观。在这个例子中,我们绘制了一个带有圆角的矩形,并在其上显示按钮文本。当按钮被按下时,其颜色会发生变化。