1

我正在使用 Pyside2,并且有一个使用 QGraphicsView 和 QGraphicsScene 的 UI。

现在我有两个独立的类,它们是 QGraphicsEllipseItem 和 QGraphicsRectItem 的子类,如下所示:

class MyRectButton(QGraphicsRectItem):

    def contextMenuEvent(self, event):
        # custom context menu
        pass

    def custom_method_A(self):
        # add a custom method
        pass

    def custom_method_B(self):
        # add a custom method
        pass

class MyEllipseButton(QGraphicsEllipseItem):

    def contextMenuEvent(self, event):
        # custom context menu
        pass

    def custom_method_A(self):
        # add a custom method
        pass

    def custom_method_B(self):
        # add a custom method
        pass

而不是在两个类中都有冗余方法,我想要一个可以是矩形或椭圆的类,例如:

class MyButton():
    def __init__(self,shape='Ellipse'):
        pass

    def contextMenuEvent(self, event):
        # custom context menu
        pass

    def custom_method_A(self):
        # add a custom method
        pass

    def custom_method_B(self):
        # add a custom method
        pass


4

1 回答 1

3

您可以创建一个实现通用功能的类,然后按钮从项目和通用类继承:

from PyQt5 import QtCore, QtWidgets


class Foo:
    def contextMenuEvent(self, event):
        print("contextMenuEvent")

    def custom_method_A(self):
        print("custom_method_A")

    def custom_method_B(self):
        print("custom_method_B")


class MyRectButton(QtWidgets.QGraphicsRectItem, Foo):
    pass


class MyEllipseButton(QtWidgets.QGraphicsEllipseItem, Foo):
    pass


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    scene = QtWidgets.QGraphicsScene()
    view = QtWidgets.QGraphicsView(scene)

    it_rect = MyRectButton(QtCore.QRectF(-50, -30, 100, 100))
    it_ellipse = MyEllipseButton(QtCore.QRectF(50, 50, 100, 100))

    scene.addItem(it_rect)
    scene.addItem(it_ellipse)

    for it in (it_rect, it_ellipse):
        it.custom_method_A()
        it.custom_method_B()

    view.resize(640, 480)
    view.show()
    sys.exit(app.exec_())
于 2020-02-26T18:19:00.200 回答