如何用多个视图正确地用PyQt5实现MVC模型?

时间:2019-01-12 20:47:09

标签: python model-view-controller pyqt5 qt-designer

这是我的第一个具有多个窗口的项目。 我正在努力正确地实现MVC模型。

user 101的帖子on this subject的大力帮助下,我开始了我的项目。它正在工作,但是我不确定MVC类的哪一部分应该处理打开新窗口。

App.py

import sys
from PyQt5 import Qt
from model.Model import Model
from ctrls.MainController import MainController
from views.MainView import MainView
from views.SettingsView import SettingsView


class App(Qt.QApplication):
    def __init__(self, sys_argv):
        super(App, self).__init__(sys_argv)
        self.model = Model()
        self.main_ctrl = MainController(self.model)
        self.main_view = MainView(self.model, self.main_ctrl)
        self.settings_view = SettingsView(self.model, self.main_ctrl)
        self.main_view.show()

        # This works, but should be shown after I pressed the Settings-button
        self.settings_view.show()


if __name__ == '__main__':
    app = App(sys.argv)
    sys.exit(app.exec_())

显然,不应立即打开设置窗口,而应在用户单击MainWindow视图上的“设置”按钮之后打开。

from PyQt5 import QtWidgets


class MainController(object):

    def __init__(self, model):
        self.model = model

    #### widget event functions ####

    def change_exit(self, checked):
        self.model.exit = checked
        print(f'DEBUG: change_exit called with arg value: {checked}')

    def change_settings(self, checked):
        self.model.settings = checked
        print(f'DEBUG: change_settings called with arg value: {checked}')

    def change_startjaar(self, index):
        self.model.startjaar = index
        print('DEBUG: change_startjaar called with arg value:', index)

    def change_startmaand(self, index):
        self.model.startmaand = index
        print('DEBUG: change_startmaand called with arg value:', index)

    def change_uurtarief(self, text):
        self.model.uurtarief = text
        print('DEBUG: change_uurtarief called with arg value:', text)

    def change_huur(self, text):
        self.model.huur = text
        print('DEBUG: change_huur called with arg value:', text)

    def change_OK(self, checked):
        self.model.OK = checked
        print('DEBUG: change_OK called with arg value:', checked)

    def change_cancel(self, checked):
        self.model.cancel = checked
        print('DEBUG: change_cancel called with arg value:', checked)

控制器接收到启动设置窗口的事件,但是由于控制器没有设置视图的句柄,因此无法启动它。

我应该提供所有视图作为对MainController的引用吗? 主App.py实例化了所有内容,因此可以正常工作,但是我不确定是否正确。请赐教。

积分

部分代码是在Github上借助this project生成的。 当我尝试仅显示相关部分时,可以找到我的整个项目over here

0 个答案:

没有答案