jeudi 14 mars 2019

MVC pattern in a wxPython application

I guess this is an evergreen topic: how to implement the MVC pattern in a wxpython app.

In my case I can sparate the model from the rest clearly. The point I struggle with is separation of the Controller and the View: it seems to me that a GUI is essentially both of these as it provides the means to control, but also it displays the model.

In my current implementation a wx.App() subclass is THE Controller, in which a bunch of method binding happens meaning, an event in the GUI triggers a method of the controller, which calls the appropriate methods within the GUI.

A simple example: saving the data.

class Controller(wx.App):

    def __init__(self, redirect=False):
        super(Controller, self).__init__(redirect)
        self.view = None  # the view
        self.model = None  # the model
        self._path_to_saved_file = None

    def start(self):
        self.model = ModelRoot()  # the model
        self.view = MainFrame(None, -1, _('App Name'), size=(1250, 690))
        self.bind_gui_elements()
        self.SetTopWindow(self.view)
        self.view.Show()
        self.MainLoop()

Binding the "File/Save" menu in self.bind_gui_elements():

self.view.Bind(wx.EVT_MENU, self.OnSave, self.view.file_menu_save)

with:

def OnSave(self, event):
    if self._path_to_saved_file is None:  # path unknown
        self.view.OnSaveAs()  # Save as dialog; returns nothing but emits a pubsub message
    self.save_to_file()  # dump the model data

In self.view OnSaveAs is implemented as a standard Save as dialog where the user can browse to the desired directory, give a name etc. This method emits a message with the user-provided path to a topic the controller is subscribed to so the attribute self._path_to_saved_file gets set. The data in self._model_description is then written to file by the Controller.

I guess this way the View and its responsibilies are clearly separated from the Controller. However, the Controller still has to know that the GUI is implemented in wxPython, and this is where I have the feeling the lines are blurred.

I have a gut feeling that further separation of the Controller and View can be done by using the pubsub messaging infrastructure, but also that this would lead to much more code to write. On the other hand the GUI moule could be anything then.

I hope my problem is described well enough to ask the question: is the current implementation correct, or does it make sense to further separate the View and Controller? Strictly following the MVC principle would require that. However I don't think I'll switch to another GUI module.

Any insight on this is highly appreciated.

Aucun commentaire:

Enregistrer un commentaire