{"id":719,"date":"2022-12-28T12:33:08","date_gmt":"2022-12-28T12:33:08","guid":{"rendered":"https:\/\/tbekk.com\/devstream\/?p=719"},"modified":"2022-12-28T12:35:29","modified_gmt":"2022-12-28T12:35:29","slug":"the-modelview-architecture","status":"publish","type":"post","link":"https:\/\/tbekk.com\/devstream\/2022\/12\/28\/the-modelview-architecture\/","title":{"rendered":"The ModelView Architecture"},"content":{"rendered":"\n<p class=\"has-medium-gray-color has-text-color has-huge-font-size\"><small><em><strong>Qt&#8217;s MVC-like interface for displaying data in views<\/strong><\/em><\/small><\/p>\n\n\n\n<hr class=\"wp-block-separator is-style-wide\"\/>\n\n\n\n<p class=\"has-medium-gray-color has-text-color\"><em>An interesting article about the MVC (Model-View-Controller) pattern and it&#8217;s usage in Qt framework using Python and PySide6 package<\/em>. <\/p>\n\n\n\n<hr class=\"wp-block-separator is-style-wide\"\/>\n\n\n\n<ul class=\"wp-block-list\"><li><em><strong>Link: <\/strong><a href=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/\" data-type=\"URL\" data-id=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/\">pythonguis.com\/tutorials\/pyside6-modelview-architecture\/<\/a><\/em><\/li><li><em><strong>Publication date: <\/strong>Augist, 11th 2022 <\/em><\/li><li><em><strong>Author: <\/strong><a href=\"https:\/\/www.pythonguis.com\/authors\/martin-fitzpatrick\/\">Martin Fitzpatrick<\/a><\/em><\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator is-style-wide\"\/>\n\n\n\n<p>As you start to build more complex applications with PySide6 you&#8217;ll likely come across issues keeping widgets in sync with your data. Data stored in widgets (e.g. a simple&nbsp;<code>QListWidget<\/code>) is not readily available to manipulate from Python \u2014&nbsp;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.<\/p>\n\n\n\n<p>Thankfully Qt has a solution for this \u2014&nbsp;ModelViews. ModelViews are a powerful alternative to the standard display widgets, which use a regular model interface to interact with data sources \u2014 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.<\/p>\n\n\n\n<p>This tutorial introduces the key aspects of Qt&#8217;s ModelView architecture and uses it to build simple desktop Todo application in PySide.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"model-view-controller\">Model View Controller<\/h2>\n\n\n\n<p><strong>Model\u2013View\u2013Controller<\/strong>&nbsp;(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.<\/p>\n\n\n\n<p>The MVC design pattern decouples three major components \u2014<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Model<\/strong>&nbsp;holds the data structure which the app is working with.<\/li><li><strong>View<\/strong>&nbsp;is any representation of information as shown to the user, whether graphical or tables. Multiple views of the same data model are allowed.<\/li><li><strong>Controller<\/strong>&nbsp;accepts input from the user, transforming it into commands to for the model or view.<\/li><\/ul>\n\n\n\n<p>It Qt land the distinction between the View &amp; 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 \u2014 called &#8220;Model View&#8221; for simplicity sake.<\/p>\n\n\n\n<p>Importantly, the distinction between the&nbsp;<em>data<\/em>&nbsp;and&nbsp;<em>how it is presented<\/em>&nbsp;is preserved.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"the-model-view\">The Model View<\/h2>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>You can use any &#8220;data store&#8221; for your model, including for example a standard Python list or dictionary, or a database (via e.g. SQLAlchemy) \u2014 it&#8217;s entirely up to you.<\/p>\n\n\n\n<p>The two parts are essentially responsible for \u2014<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>The&nbsp;<strong>model<\/strong>&nbsp;stores the data, or a reference to it and returns individual or ranges of records, and associated metadata or&nbsp;<em>display<\/em>&nbsp;instructions.<\/li><li>The&nbsp;<strong>view<\/strong>&nbsp;requests data from the model and displays what is returned on the widget.<\/li><\/ol>\n\n\n\n<p>There is an in-depth discussion of the Qt architecture&nbsp;<a href=\"http:\/\/doc.qt.io\/qt-5\/model-view-programming.html\" target=\"_blank\" rel=\"noreferrer noopener\">in the documentation<\/a>.Over&nbsp;<strong>10,000 developers<\/strong>&nbsp;have bought Create GUI Applications with Python &amp; Qt!<a href=\"https:\/\/www.pythonguis.com\/pyside6-book\/\"><\/a><a href=\"https:\/\/www.pythonguis.com\/pyside6-book\/\" target=\"_blank\" rel=\"noreferrer noopener\">More info<\/a><a href=\"https:\/\/payhip.com\/b\/vCr6q\">Get the book<\/a>Also available via&nbsp;<a href=\"https:\/\/mfitzp.gumroad.com\/l\/CHxrx\/\">Gumroad<\/a><a href=\"https:\/\/www.leanpub.com\/pyside6-book\/\">Leanpub<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a-simple-model-view-a-todo-list\">A simple Model View \u2014&nbsp;a Todo List<\/h2>\n\n\n\n<p>To demonstrate how to use the ModelViews in practise, we&#8217;ll put together a very simple implementation of a desktop Todo List. This will consist of a&nbsp;<code>QListView<\/code>&nbsp;for the list of items, a&nbsp;<code>QLineEdit<\/code>&nbsp;to enter new items, and a set of buttons to add, delete, or mark items as done.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The UI<\/h3>\n\n\n\n<p>The simple UI was laid out using Qt Creator and saved as&nbsp;<code>mainwindow.ui<\/code>. The&nbsp;<code>.ui<\/code>&nbsp;file and all the other parts can be downloaded below.<\/p>\n\n\n\n<p><a href=\"https:\/\/www.pythonguis.com\/d\/todo.zip\">Todo application Source Code<\/a><\/p>\n\n\n\n<p><img decoding=\"async\" alt=\"Designing a Simple Todo app in Qt Creator\" src=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/qt-creator.png\"><em>Designing a Simple Todo app in Qt Creator<\/em><\/p>\n\n\n\n<p>The running app is shown below.<\/p>\n\n\n\n<p><img decoding=\"async\" alt=\"The running Todo GUI (nothing works yet)\" src=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/mainwindow.png\"><em>The running Todo GUI (nothing works yet)<\/em><\/p>\n\n\n\n<p>The widgets available in the interface were given the IDs shown in the table below.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>objectName<\/th><th>Type<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>todoView<\/code><\/td><td><code>QListView<\/code><\/td><td>The list of current todos<\/td><\/tr><tr><td><code>todoEdit<\/code><\/td><td><code>QLineEdit<\/code><\/td><td>The text input for creating a new todo item<\/td><\/tr><tr><td><code>addButton<\/code><\/td><td><code>QPushButton<\/code><\/td><td>Create the new todo, adding it to the todos list<\/td><\/tr><tr><td><code>deleteButton<\/code><\/td><td><code>QPushButton<\/code><\/td><td>Delete the current selected todo, removing it from the todos list<\/td><\/tr><tr><td><code>completeButton<\/code><\/td><td><code>QPushButton<\/code><\/td><td>Mark the current selected todo as done<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We&#8217;ll use these identifiers to hook up the application logic later.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Model<\/h3>\n\n\n\n<p>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).<\/p>\n\n\n\n<p>For this example we are displaying the result to a&nbsp;<code>QListView<\/code>. The matching base model for this is&nbsp;<code>QAbstractListModel<\/code>. The outline definition for our model is shown below.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class TodoModel(QtCore.QAbstractListModel):\n    def __init__(self, *args, todos=None, **kwargs):\n        super(TodoModel, self).__init__(*args, **kwargs)\n        self.todos = todos or &#91;]\n\n    def data(self, index, role):\n        if role == Qt.DisplayRole:\n            <em># See below for the data structure.<\/em>\n            status, text = self.todos&#91;index.row()]\n            <em># Return the todo text only.<\/em>\n            return text\n\n    def rowCount(self, index):\n        return len(self.todos)\n<\/code><\/pre>\n\n\n\n<p>The<code>.todos<\/code>&nbsp;variable is our data store and the two methods&nbsp;<code>rowcount()<\/code>&nbsp;and&nbsp;<code>data()<\/code>&nbsp;are standard Model methods we must implement for a list model. We&#8217;ll go through these in turn below.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">.todos list<\/h4>\n\n\n\n<p>The data store for our model is&nbsp;<code>.todos<\/code>, a simple Python list in which we&#8217;ll store a&nbsp;<code>tuple<\/code>&nbsp;of values in the format&nbsp;<code>[(bool, str), (bool, str), (bool, str)]<\/code>&nbsp;where&nbsp;<code>bool<\/code>&nbsp;is the&nbsp;<em>done<\/em>&nbsp;state of a given entry, and&nbsp;<code>str<\/code>&nbsp;is the text of the todo.<\/p>\n\n\n\n<p>We initialise&nbsp;<code>self.todo<\/code>&nbsp;to an empty list on startup, unless a list is passed in via the&nbsp;<code>todos<\/code>&nbsp;keyword argument.<\/p>\n\n\n\n<p><code>self.todos = todos or []<\/code>&nbsp;will set&nbsp;<code>self.todos<\/code>&nbsp;to the provided todos value if it is&nbsp;<em>truthy<\/em>&nbsp;(i.e. anything other than an empty list, the boolean&nbsp;<code>False<\/code>&nbsp;or&nbsp;<code>None<\/code>&nbsp;the default value), otherwise it will be set to the empty list&nbsp;<code>[]<\/code>.<\/p>\n\n\n\n<p>To create an instance of this model we can simply do \u2014PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>model = TodoModel()   <em>#&nbsp;create an empty todo list<\/em>\n<\/code><\/pre>\n\n\n\n<p>Or to pass in an existing list \u2014PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>todos = &#91;(False, 'an item'), (False, 'another item')]\nmodel = TodoModel(todos)\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">.rowcount()<\/h4>\n\n\n\n<p>The&nbsp;<code>.rowcount()<\/code>&nbsp;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 (<code>row count-1<\/code>). Since we&#8217;re using a Python list as our data store, the return value for this is simply the&nbsp;<code>len()<\/code>&nbsp;of the list.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">.data()<\/h4>\n\n\n\n<p>This is the core of your model, which handles requests for data from the view and returns the appropriate result. It receives two parameters&nbsp;<code>index<\/code>&nbsp;and&nbsp;<code>role.<\/code><\/p>\n\n\n\n<p><code>index<\/code>&nbsp;is the position\/coordinates of the data which the view is requesting, accessible by two methods&nbsp;<code>.row()<\/code>&nbsp;and&nbsp;<code>.column()<\/code>&nbsp;which give the position in each dimension.<\/p>\n\n\n\n<p>For our&nbsp;<code>QListView<\/code>&nbsp;the column is always 0 and can be ignored, but you would need to use this for 2D data in a spreadsheet view.<\/p>\n\n\n\n<p><code>role<\/code>&nbsp;is a flag indicating the&nbsp;<em>type<\/em>&nbsp;of data the view is requesting. This is because the&nbsp;<code>.data()<\/code>&nbsp;method actually has more responsibility than just the core data. It also handles requests for style information, tooltips, status bars, etc. \u2014&nbsp;basically anything that could be informed by the data itself.<\/p>\n\n\n\n<p>The naming of&nbsp;<code>Qt.DisplayRole<\/code>&nbsp;is a bit weird, but this indicates that the&nbsp;<em>view<\/em>&nbsp;is asking us &#8220;please give me data for display&#8221;. There are other&nbsp;<em>roles<\/em>&nbsp;which the&nbsp;<code>data<\/code>&nbsp;can receive for styling requests or requesting data in &#8220;edit-ready&#8221; format.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Role<\/th><th>Value<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>Qt.DisplayRole<\/code><\/td><td><code>0<\/code><\/td><td>The key data to be rendered in the form of text. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qstring.html\" target=\"_blank\" rel=\"noreferrer noopener\">QString<\/a>)<\/td><\/tr><tr><td><code>Qt.DecorationRole<\/code><\/td><td><code>1<\/code><\/td><td>The data to be rendered as a decoration in the form of an icon. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qcolor.html\" target=\"_blank\" rel=\"noreferrer noopener\">QColor<\/a>,&nbsp;<a href=\"https:\/\/doc.qt.io\/qt-5\/qicon.html\" target=\"_blank\" rel=\"noreferrer noopener\">QIcon<\/a>&nbsp;or&nbsp;<a href=\"https:\/\/doc.qt.io\/qt-5\/qpixmap.html\" target=\"_blank\" rel=\"noreferrer noopener\">QPixmap<\/a>)<\/td><\/tr><tr><td><code>Qt.EditRole<\/code><\/td><td><code>2<\/code><\/td><td>The data in a form suitable for editing in an editor. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qstring.html\" target=\"_blank\" rel=\"noreferrer noopener\">QString<\/a>)<\/td><\/tr><tr><td><code>Qt.ToolTipRole<\/code><\/td><td><code>3<\/code><\/td><td>The data displayed in the item&#8217;s tooltip. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qstring.html\" target=\"_blank\" rel=\"noreferrer noopener\">QString<\/a>)<\/td><\/tr><tr><td><code>Qt.StatusTipRole<\/code><\/td><td><code>4<\/code><\/td><td>The data displayed in the status bar. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qstring.html\" target=\"_blank\" rel=\"noreferrer noopener\">QString<\/a>)<\/td><\/tr><tr><td><code>Qt.WhatsThisRole<\/code><\/td><td><code>5<\/code><\/td><td>The data displayed for the item in &#8220;What&#8217;s This?&#8221; mode. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qstring.html\" target=\"_blank\" rel=\"noreferrer noopener\">QString<\/a>)<\/td><\/tr><tr><td><code>Qt.SizeHintRole<\/code><\/td><td><code>13<\/code><\/td><td>The size hint for the item that will be supplied to views. (<a href=\"https:\/\/doc.qt.io\/qt-5\/qsize.html\" target=\"_blank\" rel=\"noreferrer noopener\">QSize<\/a>)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>For a full list of available&nbsp;<em>roles<\/em>&nbsp;that you can receive see&nbsp;<a href=\"https:\/\/doc.qt.io\/qt-5\/qt.html#ItemDataRole-enum\" target=\"_blank\" rel=\"noreferrer noopener\">the Qt ItemDataRole documentation<\/a>. Our todo list will only be using&nbsp;<code>Qt.DisplayRole<\/code>&nbsp;and&nbsp;<code>Qt.DecorationRole<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic implementation<\/h3>\n\n\n\n<p>Below is the basic stub application needed to load the UI and display it. We&#8217;ll add our model code and application logic to this base.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import sys\n\nfrom PySide6 import QtCore, QtGui, QtWidgets\nfrom PySide6.QtCore import Qt\n\nfrom MainWindow import Ui_MainWindow\n\n\nclass TodoModel(QtCore.QAbstractListModel):\n    def __init__(self, todos=None):\n        super().__init__()\n        self.todos = todos or &#91;]\n\n    def data(self, index, role):\n        if role == Qt.DisplayRole:\n            status, text = self.todos&#91;index.row()]\n            return text\n\n    def rowCount(self, index):\n        return len(self.todos)\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n    def __init__(self):\n        super().__init__()\n        self.setupUi(self)\n        self.model = TodoModel()\n        self.todoView.setModel(self.model)\n\n\napp = QtWidgets.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\napp.exec_()\n\n<\/code><\/pre>\n\n\n\n<p>We define our&nbsp;<code>TodoModel<\/code>&nbsp;as before, and initialise the&nbsp;<code>MainWindow<\/code>&nbsp;object. In the&nbsp;<code>__init__<\/code>&nbsp;for the MainWindow we create an instance of our todo model and set this model on the&nbsp;<code>todo_view<\/code>. Save this file as&nbsp;<code>todo.py<\/code>&nbsp;and run it with \u2014BASH<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python3 todo.py\n<\/code><\/pre>\n\n\n\n<p>While there isn&#8217;t much to see yet, the&nbsp;<code>QListView<\/code>&nbsp;and our model are actually working \u2014 if you add some default data you&#8217;ll see it appear in the list.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>self.model = TodoModel(todos=&#91;(False, 'my first todo')])\n<\/code><\/pre>\n\n\n\n<p><img decoding=\"async\" alt=\"QListView showing hard-coded todo item\" src=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/my-first-todo.png\"><em>QListView showing hard-coded todo item<\/em><\/p>\n\n\n\n<p>You can keep adding items manually like this and they will show up in order in the&nbsp;<code>QListView<\/code>. Next we&#8217;ll make it possible to add items from within the application.<\/p>\n\n\n\n<p>First create a new method on the&nbsp;<code>MainWindow<\/code>&nbsp;named&nbsp;<code>add<\/code>. 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&nbsp;<code>addButton.pressed<\/code>&nbsp;signal at the end of the&nbsp;<code>__init__<\/code>&nbsp;block.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n    def __init__(self):\n        QtWidgets.QMainWindow.__init__(self)\n        Ui_MainWindow.__init__(self)\n        self.setupUi(self)\n        self.model = TodoModel()\n        self.todoView.setModel(self.model)\n        <em># Connect the button.<\/em>\n            self.addButton.pressed.connect(self.add)\n\n    def add(self):\n        \"\"\"\n        Add an item to our todo list, getting the text from the QLineEdit .todoEdit\n        and then clearing it.\n        \"\"\"\n        text = self.todoEdit.text()\n        if text: <em># Don't add empty strings.<\/em>\n            <em># Access the list via the model.<\/em>\n            self.model.todos.append((False, text))\n            <em># Trigger refresh.<\/em>\n            self.model.layoutChanged.emit()\n            <em>#&nbsp;Empty the input<\/em>\n            self.todoEdit.setText(\"\")\n\n<\/code><\/pre>\n\n\n\n<p>In the&nbsp;<code>add<\/code>&nbsp;block notice the line&nbsp;<code>self.model.layoutChanged.emit()<\/code>. Here we&#8217;re emitting a model signal&nbsp;<code>.layoutChanged<\/code>&nbsp;to let the view know that the&nbsp;<em>shape<\/em>&nbsp;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&nbsp;<code>QListView<\/code>&nbsp;won&#8217;t update.<\/p>\n\n\n\n<p>If just the data is altered, but the number of rows\/columns are unaffected you can use the&nbsp;<code>.dataChanged()<\/code>&nbsp;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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Hooking up the other actions<\/h3>\n\n\n\n<p>We can now connect the rest of the button&#8217;s signals and add helper functions for performing the&nbsp;<em>delete<\/em>&nbsp;and&nbsp;<em>complete<\/em>&nbsp;operations. We add the button signals to the&nbsp;<code>__init__<\/code>&nbsp;block as before.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        self.addButton.pressed.connect(self.add)\n        self.deleteButton.pressed.connect(self.delete)\n        self.completeButton.pressed.connect(self.complete)\n<\/code><\/pre>\n\n\n\n<p>Then define a new&nbsp;<code>delete<\/code>&nbsp;method as follows \u2014PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    def delete(self):\n        indexes = self.todoView.selectedIndexes()\n        if indexes:\n            <em># Indexes is a list of a single item in single-select mode.<\/em>\n            index = indexes&#91;0]\n            <em># Remove the item and refresh.<\/em>\n            del self.model.todos&#91;index.row()]\n            self.model.layoutChanged.emit()\n            <em># Clear the selection (as it is no longer valid).<\/em>\n            self.todoView.clearSelection()\n\n<\/code><\/pre>\n\n\n\n<p>We use&nbsp;<code>self.todoView.selectedIndexes<\/code>&nbsp;to get the indexes (actually a list of a single item, as we&#8217;re in single-selection mode) and then use the&nbsp;<code>.row()<\/code>&nbsp;as an index into our list of todos on our model. We delete the indexed item using Python&#8217;s&nbsp;<code>del<\/code>&nbsp;operator, and then trigger a&nbsp;<code>layoutChanged<\/code>&nbsp;signal because the shape of the data has been modified.<\/p>\n\n\n\n<p>Finally, we clear the active selection since the item it relates to may now out of bounds (if you had selected the last item).<\/p>\n\n\n\n<p>You could try make this smarter, and select the last item in the list instead<\/p>\n\n\n\n<p>The&nbsp;<code>complete<\/code>&nbsp;method looks like this \u2014PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\n    def complete(self):\n        indexes = self.todoView.selectedIndexes()\n        if indexes:\n            index = indexes&#91;0]\n            row = index.row()\n            status, text = self.model.todos&#91;row]\n            self.model.todos&#91;row] = (True, text)\n            <em># .dataChanged takes top-left and bottom right, which are equal<\/em>\n            <em># for a single selection.<\/em>\n            self.model.dataChanged.emit(index, index)\n            <em># Clear the selection (as it is no longer valid).<\/em>\n            self.todoView.clearSelection()\n<\/code><\/pre>\n\n\n\n<p>This uses the same indexing as for delete, but this time we fetch the item from the model&nbsp;<code>.todos<\/code>&nbsp;list and then replace the status with&nbsp;<code>True<\/code>.<\/p>\n\n\n\n<p>We have to do this fetch-and-replace, as our data is stored as Python tuples which cannot be modified.<\/p>\n\n\n\n<p>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 \u2014 updating the widget state is handled automatically.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using Qt.DecorationRole<\/h3>\n\n\n\n<p>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.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>tick = QtGui.QImage('tick.png')\n\n\nclass TodoModel(QtCore.QAbstractListModel):\n    def __init__(self, *args, todos=None, **kwargs):\n        super(TodoModel, self).__init__(*args, **kwargs)\n        self.todos = todos or &#91;]\n\n    def data(self, index, role):\n        if role == Qt.DisplayRole:\n            _, text = self.todos&#91;index.row()]\n            return text\n\n        if role == Qt.DecorationRole:\n            status, _ = self.todos&#91;index.row()]\n            if status:\n                return tick\n\n    def rowCount(self, index):\n        return len(self.todos)\n\n<\/code><\/pre>\n\n\n\n<p>We&#8217;re using a tick icon&nbsp;<code>tick.png<\/code>&nbsp;to indicate completed items, which we load into a&nbsp;<code>QImage<\/code>&nbsp;object named&nbsp;<code>tick<\/code>. In the model we&#8217;ve implemented a handler for the&nbsp;<code>Qt.DecorationRole<\/code>&nbsp;which returns the tick icon for rows who&#8217;s&nbsp;<code>status<\/code>&nbsp;is&nbsp;<code>True<\/code>&nbsp;(for complete).<\/p>\n\n\n\n<p>The icon I&#8217;m using is taken from the Fugue set by&nbsp;<a href=\"http:\/\/p.yusukekamiyamane.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">p.yusukekamiyamane<\/a><\/p>\n\n\n\n<p>Instead of an icon you can also return a color, e.g.&nbsp;<code>QtGui.QColor('green')<\/code>&nbsp;which will be drawn as solid square.<\/p>\n\n\n\n<p>Running the app you should now be able to mark items as complete.<\/p>\n\n\n\n<p><img decoding=\"async\" alt=\"Todos Marked Complete\" src=\"https:\/\/www.pythonguis.com\/tutorials\/pyside6-modelview-architecture\/todos_complete.png\"><em>Todos Marked Complete<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"a-persistent-data-store\">A persistent data store<\/h2>\n\n\n\n<p>Our todo app works nicely, but it has one fatal flaw \u2014&nbsp;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&#8217;s probably a bad idea.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>To do this we define two new methods on our&nbsp;<code>MainWindow<\/code>&nbsp;class&nbsp;\u2014&nbsp;<code>load<\/code>&nbsp;and&nbsp;<code>save<\/code>. These load data from a JSON file name&nbsp;<code>data.json<\/code>&nbsp;(if it exists, ignoring the error if it doesn&#8217;t) to&nbsp;<code>self.model.todos<\/code>&nbsp;and write the current&nbsp;<code>self.model.todos<\/code>&nbsp;out to the same file, respectively.PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    def load(self):\n        try:\n            with open('data.json', 'r') as f:\n                self.model.todos = json.load(f)\n        except Exception:\n            pass\n\n    def save(self):\n        with open('data.json', 'w') as f:\n            data = json.dump(self.model.todos, f)\n<\/code><\/pre>\n\n\n\n<p>To persist the changes to the data we need to add the&nbsp;<code>.save()<\/code>&nbsp;handler to the end of any method that modifies the data, and the&nbsp;<code>.load()<\/code>&nbsp;handler to the&nbsp;<code>__init__<\/code>&nbsp;block after the model has been created.<\/p>\n\n\n\n<p>The final code looks like this \u2014PYTHON<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\nimport sys\n\nfrom PySide6 import QtCore, QtGui, QtWidgets\nfrom PySide6.QtCore import Qt\n\nfrom MainWindow import Ui_MainWindow\n\ntick = QtGui.QImage(\"tick.png\")\n\n\nclass TodoModel(QtCore.QAbstractListModel):\n    def __init__(self, todos=None):\n        super().__init__()\n        self.todos = todos or &#91;]\n\n    def data(self, index, role):\n        if role == Qt.DisplayRole:\n            _, text = self.todos&#91;index.row()]\n            return text\n\n        if role == Qt.DecorationRole:\n            status, _ = self.todos&#91;index.row()]\n            if status:\n                return tick\n\n    def rowCount(self, index):\n        return len(self.todos)\n\n\nclass MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):\n    def __init__(self):\n        super().__init__()\n\n        self.setupUi(self)\n        self.model = TodoModel()\n        self.load()\n        self.todoView.setModel(self.model)\n        self.addButton.pressed.connect(self.add)\n        self.deleteButton.pressed.connect(self.delete)\n        self.completeButton.pressed.connect(self.complete)\n\n    def add(self):\n        \"\"\"\n        Add an item to our todo list, getting the text from the QLineEdit .todoEdit\n        and then clearing it.\n        \"\"\"\n        text = self.todoEdit.text()\n        if text:  <em># Don't add empty strings.<\/em>\n            <em># Access the list via the model.<\/em>\n            self.model.todos.append((False, text))\n            <em># Trigger refresh.<\/em>\n            self.model.layoutChanged.emit()\n            <em># Empty the input<\/em>\n            self.todoEdit.setText(\"\")\n            self.save()\n\n    def delete(self):\n        indexes = self.todoView.selectedIndexes()\n        if indexes:\n            <em># Indexes is a list of a single item in single-select mode.<\/em>\n            index = indexes&#91;0]\n            <em># Remove the item and refresh.<\/em>\n            del self.model.todos&#91;index.row()]\n            self.model.layoutChanged.emit()\n            <em># Clear the selection (as it is no longer valid).<\/em>\n            self.todoView.clearSelection()\n            self.save()\n\n    def complete(self):\n        indexes = self.todoView.selectedIndexes()\n        if indexes:\n            index = indexes&#91;0]\n            row = index.row()\n            status, text = self.model.todos&#91;row]\n            self.model.todos&#91;row] = (True, text)\n            <em># .dataChanged takes top-left and bottom right, which are equal<\/em>\n            <em># for a single selection.<\/em>\n            self.model.dataChanged.emit(index, index)\n            <em># Clear the selection (as it is no longer valid).<\/em>\n            self.todoView.clearSelection()\n            self.save()\n\n    def load(self):\n        try:\n            with open(\"data.json\", \"r\") as f:\n                self.model.todos = json.load(f)\n        except Exception:\n            pass\n\n    def save(self):\n        with open(\"data.json\", \"w\") as f:\n            data = json.dump(self.model.todos, f)\n\n\napp = QtWidgets.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\napp.exec_()\n\n\n<\/code><\/pre>\n\n\n\n<p>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&#8217;ll cover how to do this in an upcoming tutorial.<\/p>\n\n\n\n<p>For another interesting example of a&nbsp;<code>QListView<\/code>&nbsp;see&nbsp;<a href=\"https:\/\/www.pythonguis.com\/examples\/failamp-multimedia-player\/\">this example media player application<\/a>. It uses the Qt built-in&nbsp;<code>QMediaPlaylist<\/code>&nbsp;as the datastore, with the contents displayed to a&nbsp;<code>QListView<\/code>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Qt&#8217;s MVC-like interface for displaying data in views An interesting article about the MVC (Model-View-Controller) pattern and it&#8217;s usage in Qt framework using Python and PySide6 package. Link: pythonguis.com\/tutorials\/pyside6-modelview-architecture\/ Publication&#8230; <a class=\"read-more-link\" href=\"https:\/\/tbekk.com\/devstream\/2022\/12\/28\/the-modelview-architecture\/\">Read more &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[51,172,10,11,54],"tags":[138,170,169,171,55],"class_list":["post-719","post","type-post","status-publish","format-standard","hentry","category-article","category-design-patterns","category-development","category-qt","category-ui","tag-gui","tag-model-view-controller","tag-mvc","tag-pyside","tag-qt"],"_links":{"self":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/719","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/comments?post=719"}],"version-history":[{"count":1,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/719\/revisions"}],"predecessor-version":[{"id":720,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/posts\/719\/revisions\/720"}],"wp:attachment":[{"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/media?parent=719"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/categories?post=719"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/tbekk.com\/devstream\/wp-json\/wp\/v2\/tags?post=719"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}