首页 > 解决方案 > 如何使用 QPushButton 在 PyQt5 的 QStackedLayout 中切换索引 - 为什么我的 MVC 控制器不起作用?

问题描述

我目前正在学习 PyQt5,并且正在努力解决如何使用 a QStackedLayout- 特别是如何通过使用信号和插槽模型的按钮按下来设置堆叠布局的当前索引。

这是一个显示我的问题的最小示例。

import sys  # used to handle application exit

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtWidgets import QPushButton, QLabel
from PyQt5.QtWidgets import QStackedLayout, QVBoxLayout


# GUI
class UI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setFixedSize(1024, 600)
        # central widget
        self._centralWidget = QWidget(self)
        self.setCentralWidget(self._centralWidget)
        # general layout
        self._generalLayout = QVBoxLayout()
        self._centralWidget.setLayout(self._generalLayout)
        # ui elements
        self._createHeader()
        self._createMainScreen()

    def _createHeader(self):
        """Create the GUI's header"""
        self.switchscreenbutton = QPushButton()
        self.switchscreenbutton.setText("SWITCH")
        self._generalLayout.addWidget(self.switchscreenbutton)

    def _createMainScreen(self):
        """Create the GUI's control screen"""
        self.screens = []
        self.screenslayout = QStackedLayout()

        self._createControlScreen(self.screenslayout)
        self._createSettingsScreen(self.screenslayout)

        self._generalLayout.addLayout(self.screenslayout)

    def _createControlScreen(self, container):
        templabel = QLabel()
        templabel.setText("CONTROL")
        container.addWidget(templabel)

    def _createSettingsScreen(self, container):
        templabel = QLabel()
        templabel.setText("SETTINGS")
        container.addWidget(templabel)


# CONTROLLER
class Control:
    def __init__(self, model, view):
        self._model = model
        self._view = view
        # connect signals and slots (MVC framework used by PyQt5)
        self._connectSignals()

    def _connectSignals(self):
        self._view.switchscreenbutton.clicked.connect(self._switchscreen)

    def _switchscreen(self):
        if self._view.screenslayout.currentIndex() == 1:
            self._view.screenslayout.setCurrentIndex(0)
        else:
            self._view.screenslayout.setCurrentIndex(1)


# Client code
def main():
    """Main function"""
    app = QApplication(sys.argv)
    # show GUI
    gui = UI()
    gui.show()
    # model and controller
    model = None    # TODO
    Control(model=model, view=gui)
    # execute event loop
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

总而言之,我在堆叠布局上方有一个按钮。堆叠布局根据布局的当前索引显示不同的标签。单击按钮时,会调用Control'_switchscreen()方法(这是在Control's中设置的_connectSignals(),它应该相应地设置布局的当前索引。

标签: pythonpyqt5

解决方案


问题是 Control 对象未分配给变量,然后它将被销毁,因此其方法将不起作用。解决方案是:

control = Control(model=model, view=gui)

推荐阅读