PyQt-轻松将QWidget添加到所有视图

时间:2019-04-06 21:02:47

标签: python pyqt pyqt5

我有以下

class MyView(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        layout = QVBoxLayout()
        layout.addWidget(QLabel('Hello World'))
        self.setLayout(layout)


class NavigationMenu(QWidget):
    pass
    # Renders a bar of full width and 15 px height

NavigationMenu添加到MyView的最简单方法是什么?

将来,我还必须将NavigationMenu添加到所有其他视图中,因此我正在从打字和可维护性的角度寻找可扩展的东西。

我尝试了装饰器(仅在类顶部使用@NavigationMenuDecorator),但是我要么无法绑定它们,要么它们在解析时被初始化并且错误QWidget: Must construct a QApplication before a QWidget

我尝试将其添加到MyView中,但是有很多样板

class MyWidget(Widget.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        layout = Widget.QVBoxLayout()
        layout.addWidget(QLabel('Hello World'))

        topLayout = Widget.QVBoxLayout()
        topLayout.setContentsMargins(0, 0, 0, 0)
        topLayout.addWidget(NavigationMenu())
        topLayout.addLayout(layout)

        self.setLayout(topLayout)

2 个答案:

答案 0 :(得分:3)

可能的解决方案是使用元类:

from PyQt5 import QtCore, QtWidgets

class NavigationMenu(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(QtWidgets.QLabel("NavigationMenu"))

class MetaNavigationMenu(type(QtWidgets.QWidget), type):
    def __call__(cls, *args, **kw):
        obj = super().__call__(*args, **kw)
        lay = obj.layout()
        if lay is not None:
            lay.addWidget(NavigationMenu())
        return obj

class View(QtWidgets.QWidget, metaclass=MetaNavigationMenu):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(QtWidgets.QLabel('Hello World'))
        self.setLayout(layout)

if __name__=="__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = View()
    w.show()
    sys.exit(app.exec_())

更新

使用以下方法,可以注入视图以及该视图所需的其他参数:

from PyQt5 import QtCore, QtWidgets

class NavigationMenu(QtWidgets.QWidget):
    def __init__(self, value, text="", parent=None):
        super().__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(QtWidgets.QLabel(text))
        print(value)

class MetaMenu(type(QtWidgets.QWidget), type):
    def __new__(cls, class_name, parents, attrs, **kwargs):
        cls._view = kwargs.pop('view', None)
        cls._args = kwargs.pop('args', tuple())
        cls._kwargs = kwargs.pop('kwargs', dict())
        return type.__new__(cls, class_name, parents, attrs)

    def __call__(cls, *args, **kw):
        obj = super().__call__(*args, **kw)
        layout = getattr(obj, 'layout', None)
        if callable(layout) and View is not None:
            layout().addWidget(cls._view(*cls._args, **cls._kwargs))
        return obj

class View(QtWidgets.QWidget, metaclass=MetaMenu, view=NavigationMenu, args=(10, ), kwargs={"text": "NavigationMenu"}):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(QtWidgets.QLabel('Hello World'))
        self.setLayout(layout)

if __name__=="__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = View()
    w.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

这里的另一个解决方案是惊人的,我学到了很多有关元类的知识。但是,它很难阅读并且增加了不必要的复杂性。我选择了一种基于合成的方法,只是将样板提取到一个单独的函数中。

add_navigation()函数将旧布局包装在小部件中,使用NavigationMenu和旧布局创建QVBoxLayout,最后交换布局。

def add_navigation(widget, title)
    main = QWidget()
    main.setLayout(widget.layout())

    layout = QVBoxLayout()
    layout.setContentsMargins(0, 0, 0, 0)
    layout.setSpacing(0)
    layout.addWidget(NavigationBar(title))
    layout.addWidget(main)

    widget.setLayout(layout)

然后我们只有一个样板,并且代码变成了。

class MyView(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        layout = QVBoxLayout()
        layout.addWidget(QLabel('Hello World'))
        self.setLayout(layout)

        add_navigation(self, 'Navigation Title')


class NavigationMenu(QWidget):
    pass
    # Renders a bar of full width and 15 px height