转载: Using the PySide6 ModelView Architecture to build a simple Todo app
As you start to build more complex applications with PySide6 you’ll likely come across issues keeping widgets in sync with your data. Data stored in widgets (e.g. a simple QListWidget
) is not readily available to manipulate from Python — changes require you to get an item, get the data, and then set it back. The default solution to this is to keep an external data representation in Python, and then either duplicate updates to the both the data and the widget, or simply rewrite the whole widget from the data. This can get ugly quickly, and results in a lot of boilerplate just for fiddling the data.
Thankfully Qt has a solution for this — ModelViews. ModelViews are a powerful alternative to the standard display widgets, which use a regular model interface to interact with data sources — from simple data structures to external databases. This isolates your data, allowing it to be kept in any structure you like, while the view takes care of presentation and updates.
This tutorial introduces the key aspects of Qt’s ModelView architecture and uses it to build simple desktop Todo application in PySide.
# Model View Controller
Model–View–Controller (MVC) is an architectural pattern used for developing user interfaces which divides an application into three interconnected parts. This separates the internal representation of data from how information is presented to and accepted from the user.
The MVC design pattern decouples three major components —
- Model holds the data structure which the app is working with.
- View is any representation of information as shown to the user, whether graphical or tables. Multiple views of the same data model are allowed.
- Controller accepts input from the user, transforming it into commands to for the model or view.
It Qt land the distinction between the View & Controller gets a little murky. Qt accepts input events from the user (via the OS) and delegates these to the widgets (Controller) to handle. However, widgets also handle presentation of the current state to the user, putting them squarely in the View. Rather than agonize over where to draw the line, in Qt-speak the View and Controller are instead merged together creating a Model/ViewController architecture — called “Model View” for simplicity sake.
Importantly, the distinction between the data and how it is presented is preserved.
# The Model View
The Model acts as the interface between the data store and the ViewController. The Model holds the data (or a reference to it) and presents this data through a standardised API which Views then consume and present to the user. Multiple Views can share the same data, presenting it in completely different ways.
You can use any “data store” for your model, including for example a standard Python list or dictionary, or a database (via e.g. SQLAlchemy) — it’s entirely up to you.
The two parts are essentially responsible for —
- The model stores the data, or a reference to it and returns individual or ranges of records, and associated metadata or display instructions.
- The view requests data from the model and displays what is returned on the widget.
# A simple Model View — a Todo List
To demonstrate how to use the ModelViews in practise, we’ll put together a very simple implementation of a desktop Todo List. This will consist of a QListView
for the list of items, a QLineEdit
to enter new items, and a set of buttons to add, delete, or mark items as done.
# The UI
The simple UI was laid out using Qt Creator and saved as mainwindow.ui
. The .ui
file and all the other parts can be downloaded below.
Todo application Source Code
_Designing a Simple Todo app in Qt Creator_The running app is shown below.
The running Todo GUI (nothing works yet)
The widgets available in the interface were given the IDs shown in the table below.
objectName | Type | Description |
---|---|---|
todoView |
QListView |
The list of current todos |
todoEdit |
QLineEdit |
The text input for creating a new todo item |
addButton |
QPushButton |
Create the new todo, adding it to the todos list |
deleteButton |
QPushButton |
Delete the current selected todo, removing it from the todos list |
completeButton |
QPushButton |
Mark the current selected todo as done |
We’ll use these identifiers to hook up the application logic later.
# The Model
We define our custom model by subclassing from a base implementation, allowing us to focus on the parts unique to our model. Qt provides a number of different model bases, including lists, trees and tables (ideal for spreadsheets).
For this example we are displaying the result to a QListView
. The matching base model for this is QAbstractListModel
. The outline definition for our model is shown below.
1 | class TodoModel(QtCore.QAbstractListModel): |
The .todos
variable is our data store and the two methods rowcount()
and data()
are standard Model methods we must implement for a list model. We’ll go through these in turn below.
# .todos list
The data store for our model is .todos
, a simple Python list in which we’ll store a tuple
of values in the format [(bool, str), (bool, str), (bool, str)]
where bool
is the done state of a given entry, and str
is the text of the todo.
We initialise self.todo
to an empty list on startup, unless a list is passed in via the todos
keyword argument.
self.todos = todos or []
will set self.todos
to the provided todos value if it is truthy (i.e. anything other than an empty list, the boolean False
or None
the default value), otherwise it will be set to the empty list []
.
To create an instance of this model we can simply do —
1 | model = TodoModel() # create an empty todo list |
Or to pass in an existing list —
1 | todos = [(False, 'an item'), (False, 'another item')] |
# .rowcount()
The .rowcount()
method is called by the view to get the number of rows in the current data. This is required for the view to know the maximum index it can request from the data store ( row count-1
). Since we’re using a Python list as our data store, the return value for this is simply the len()
of the list.
# .data()
This is the core of your model, which handles requests for data from the view and returns the appropriate result. It receives two parameters index
and role.
index
is the position/coordinates of the data which the view is requesting, accessible by two methods .row()
and .column()
which give the position in each dimension.
For our QListView
the column is always 0 and can be ignored, but you would need to use this for 2D data in a spreadsheet view.
role
is a flag indicating the type of data the view is requesting. This is because the .data()
method actually has more responsibility than just the core data. It also handles requests for style information, tooltips, status bars, etc. — basically anything that could be informed by the data itself.
The naming of Qt.DisplayRole
is a bit weird, but this indicates that the view is asking us “please give me data for display”. There are other roles which the data
can receive for styling requests or requesting data in “edit-ready” format.
Role | Value | Description |
---|---|---|
Qt.DisplayRole |
0 |
The key data to be rendered in the form of text. (QString) |
Qt.DecorationRole |
1 |
The data to be rendered as a decoration in the form of an icon. (QColor, QIcon or QPixmap) |
Qt.EditRole |
2 |
The data in a form suitable for editing in an editor. (QString) |
Qt.ToolTipRole |
3 |
The data displayed in the item’s tooltip. (QString) |
Qt.StatusTipRole |
4 |
The data displayed in the status bar. (QString) |
Qt.WhatsThisRole |
5 |
The data displayed for the item in “What’s This?” mode. (QString) |
Qt.SizeHintRole |
13 |
The size hint for the item that will be supplied to views. (QSize) |
For a full list of available roles that you can receive see the Qt ItemDataRole documentation. Our todo list will only be using Qt.DisplayRole
and Qt.DecorationRole
.
# Basic implementation
Below is the basic stub application needed to load the UI and display it. We’ll add our model code and application logic to this base.
1 | import sys |
We define our TodoModel
as before, and initialise the MainWindow
object. In the __init__
for the MainWindow we create an instance of our todo model and set this model on the todo_view
. Save this file as todo.py
and run it with —
BASH
1 | python3 todo.py |
While there isn’t much to see yet, the QListView
and our model are actually working — if you add some default data you’ll see it appear in the list.
1 | self.model = TodoModel(todos=[(False, 'my first todo')]) |
You can keep adding items manually like this and they will show up in order in the QListView
. Next we’ll make it possible to add items from within the application.
First create a new method on the MainWindow
named add
. This is our callback which will take care of adding the current text from the input as a new todo. Connect this method to the addButton.pressed
signal at the end of the __init__
block.
1 | class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): |
In the add
block notice the line self.model.layoutChanged.emit()
. Here we’re emitting a model signal .layoutChanged
to let the view know that the shape of the data has been altered. This triggers a refresh of the entirety of the view. If you omit this line, the todo will still be added but the QListView
won’t update.
If just the data is altered, but the number of rows/columns are unaffected you can use the .dataChanged()
signal instead. This also defines an altered region in the data using a top-left and bottom-right location to avoid redrawing the entire view.
# Hooking up the other actions
We can now connect the rest of the button’s signals and add helper functions for performing the delete and complete operations. We add the button signals to the __init__
block as before.
1 | self.addButton.pressed.connect(self.add) |
Then define a new delete
method as follows —
1 | def delete(self): |
We use self.todoView.selectedIndexes
to get the indexes (actually a list of a single item, as we’re in single-selection mode) and then use the .row()
as an index into our list of todos on our model. We delete the indexed item using Python’s del
operator, and then trigger a layoutChanged
signal because the shape of the data has been modified.
Finally, we clear the active selection since the item it relates to may now out of bounds (if you had selected the last item).
You could try make this smarter, and select the last item in the list instead
The complete
method looks like this —
1 | def complete(self): |
This uses the same indexing as for delete, but this time we fetch the item from the model .todos
list and then replace the status with True
.
We have to do this fetch-and-replace, as our data is stored as Python tuples which cannot be modified.
The key difference here vs. standard Qt widgets is that we make changes directly to our data, and simply need to notify Qt that some change has occurred — updating the widget state is handled automatically.
# Using Qt.DecorationRole
If you run the application now you should find that adding and deleting both work, but while completing items is working, there is no indication of it in the view. We need to update our model to provide the view with an indicator to display when an item is complete. The updated model is shown below.
1 | tick = QtGui.QImage('tick.png') |
We’re using a tick icon tick.png
to indicate completed items, which we load into a QImage
object named tick
. In the model we’ve implemented a handler for the Qt.DecorationRole
which returns the tick icon for rows who’s status
is True
(for complete).
The icon I’m using is taken from the Fugue set by p.yusukekamiyamane
Instead of an icon you can also return a color, e.g. QtGui.QColor('green')
which will be drawn as solid square.
Running the app you should now be able to mark items as complete.
_Todos Marked Complete_# A persistent data store
Our todo app works nicely, but it has one fatal flaw — it forgets your todos as soon as you close the application While thinking you have nothing to do when you do may help to contribute to short-term feelings of Zen, long term it’s probably a bad idea.
The solution is to implement some sort of persistent data store. The simplest approach is a simple file store, where we load items from a JSON or Pickle file at startup, and write back on changes.
To do this we define two new methods on our MainWindow
class — load
and save
. These load data from a JSON file name data.json
(if it exists, ignoring the error if it doesn’t) to self.model.todos
and write the current self.model.todos
out to the same file, respectively.
1 | def load(self): |
To persist the changes to the data we need to add the .save()
handler to the end of any method that modifies the data, and the .load()
handler to the __init__
block after the model has been created.
The final code looks like this —
1 | import json |
If the data in your application has the potential to get large or more complex, you may prefer to use an actual database to store it. In this case the model will wrap the interface to the database and query it directly for data to display. I’ll cover how to do this in an upcoming tutorial.
For another interesting example of a QListView
see this example media player application. It uses the Qt built-in QMediaPlaylist
as the datastore, with the contents displayed to a QListView
.
# Coments
todo.py
1 | import sys |
tick.png
todo.ui1 |
|
Ui_todo.py
1 | # -*- coding: utf-8 -*- |