Main Content

Model - View - Controller demo, Sqlite - Python 3 - Qt4

Archive - Originally posted on "The Horse's Mouth" - 2010-04-29 22:41:49 - Graham Ellis

The Model - View - Controller approach to application design keeps the Graphic User Interface (the view) separate from the database (the model), with the controller in between the two, describing how the data is displayed, and how changes to the data are saved away in the database. By separating the elements in this way, extra displays can be added and removed, and the look and feel can be changed, without effecting the underlying data structure. And algorithms that deal with the data can be amended (and re-used away from the GUI) without effecting the GUIs.

It's a grand theory ... but do I have a small, practical first example in [LANGUAGE] using the [GUINAME] GUI and the [DATABASE] database? That's a question I'm often asked ... and today I put together such an example where the answers were:
  • Python 3 for the language
  • Qt4 (via PyQt) for the GUI
  • SQlite for the database.

This is what the application looks like when it's run - the view. It's displaying the list of hotel names from the database - the model - through a piece of logic which extracts each hotel via a hotel object and converts it into the string to be displayed - the controller.


There are four files in the main application - there's [model.py] which fetches all the hotel objects from the SQlite database. There's [tourist.py] which defines the hotel objects in the model. There's the controller which generates the list for display at [accomlist.py], and there's the view which is at [ticfull.py].

You'll find two more files associated with this demonstration - there's a second (simpler) view to illustrate how it broadens out to show the model in different ways - that's at [tic_view.py] and there's [sqlite.py] which is a separate program to populate the database.