python qpushbutton的自定義繪制如何實(shí)現(xiàn)

小樊
83
2024-09-06 15:57:32

要在PyQt5中自定義繪制QPushButton,你需要?jiǎng)?chuàng)建一個(gè)新的類,該類繼承自QPushButton,并重寫(xiě)其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):
        # 創(chuàng)建一個(gè)QPainter對(duì)象
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 設(shè)置繪制按鈕時(shí)的顏色和樣式
        if self.isDown():
            painter.setBrush(QColor(100, 100, 100))
        else:
            painter.setBrush(QColor(200, 200, 200))

        # 繪制按鈕的外觀
        painter.drawRoundedRect(self.rect(), 5, 5)

        # 設(shè)置文本顏色和字體
        pen = painter.pen()
        pen.setColor(Qt.black)
        painter.setPen(pen)
        font = QFont("Arial", 12)
        painter.setFont(font)

        # 計(jì)算文本的位置
        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__()

        # 創(chuàng)建自定義按鈕
        custom_button = CustomPushButton("Custom Button")
        custom_button.clicked.connect(self.on_custom_button_clicked)

        # 創(chuàng)建默認(rèn)按鈕
        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_())

這個(gè)示例展示了如何創(chuàng)建一個(gè)自定義的QPushButton子類(CustomPushButton),并重寫(xiě)其paintEvent方法以自定義按鈕的外觀。在這個(gè)例子中,我們繪制了一個(gè)帶有圓角的矩形,并在其上顯示按鈕文本。當(dāng)按鈕被按下時(shí),其顏色會(huì)發(fā)生變化。

0