要在PyQt5中為QPushButton設置自定義形狀,您需要創建一個自定義按鈕類并重寫paintEvent()方法。以下是一個示例,展示了如何創建一個圓形QPushButton:
import sys
from PyQt5.QtCore import Qt, QPointF
from PyQt5.QtGui import QPainter, QBrush, QPen
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class CircleButton(QPushButton):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(100, 100)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
brush = QBrush(Qt.blue)
pen = QPen(Qt.black)
pen.setWidth(2)
painter.setBrush(brush)
painter.setPen(pen)
center = QPointF(self.width() / 2, self.height() / 2)
radius = min(self.width(), self.height()) / 2 - pen.width() / 2
painter.drawEllipse(center, radius, radius)
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
self.circle_button = CircleButton()
layout.addWidget(self.circle_button)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
這個示例創建了一個名為CircleButton的自定義QPushButton類。在paintEvent()方法中,我們使用QPainter繪制一個藍色的圓形按鈕,邊界為黑色。然后,在MainWindow類中,我們創建了一個CircleButton實例并將其添加到布局中。
您可以根據需要修改paintEvent()方法以繪制不同的形狀。