Section 15.23 PyQt (Python + Qt) learning portal: development using Model / View architecture QListView view of supporting Model

I. Overview

QListView is theoretically possible and all QAbstractItemModel derived classes such as QStringListModel, QDirModel, QFileSystemModel, QStandardItemModel such as docking, but QListView can actually show data only a little for complex hierarchical tree using the Model using QListView to show significance. This section describes the process to QListView / Model developed by several cases of simple code.

二、QListView/QStringListModel

2.1, QStringListModel introduction

QStringListModel Qt has been achieved is provided a QAbstractItemModel Model of interfaces, adapted to show a series of simplified view of the object and the character string as QListView QComboBox objects.

Providing all the standard functions QStringListModel editable model, the data is stored as a list of strings in a plurality of rows model.

Use index (int row, int column = 0, QModelIndex parent = () QModelIndex) acquires model index function corresponding to the entry, using flags (QModelIndex index) acquired item flag; use data () function to read the data item, and the setData () writes the data item using the rowCount () function to access the number of rows in the data model.

The model can be used to construct an existing list of strings, or can setStringList () function to set the string. String may be () function in the usual manner for inserting insertRows, and remove by removeRows (). You can use the contents list of strings stringList () function to retrieve.

2.2, using the Model QStringListModel as QListView

Model approach using QStringListModel as QListView is very simple, first create QStringListModel instance of the object, if the data is not stored in the data is stored in the Model to Model, and then set QListView object Model Model instance you just created. Proceed as follows:

2.2.1, to create an object instance QStringListModel

There are two ways to create an object instance:

  • Creating Data Model no
    syntax is: QStringListModel (QObject parent = None)
  • Creating Model while initializing data
    syntax is: QStringListModel (strings, QObject parent = None)
    in which the strings for the data to show a list of strings.
2.2.2, the data model is initialized

If no data model created, you can initialize the data model in several ways:

  • Use setStringList (str) to complete initialization method, the sample code:
self.model1.setStringList(["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"])
  • Use insertRows (), index (), setData () method of a combination
    of data insertRows is to insert an empty record in the data model, the data only occupies positions, but no actual data needs to be generated by the actual storage of setData. This combination of methods have little practical value, the meaning of specific parameters and methods described herein without detail.

  • SetModel to use a view (model) method to establish a connection model and view

2.2.3, sample code and run shot

This code uses to create an object and then using the method of initialization data setStringList:

 def initStringListModel(self):
        strList = ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"]
        self.model = QStringListModel()
        self.model.setStringList(strList )
        self.listView.setModel(self.model)

Run shot:
Here Insert Picture Description

三、QListView/QFileSystemModel

3.1 Overview

QFileSystemModel provides a model class specified in the local file system directory tree file structure for storing files list, which provides access to the local file system, providing rename and delete files and directories as well as create a new directory function. In the simplest case, it can serve as part of a browser, or with an appropriate filter means for use with the display.

Although QListView is a single-level view, QFileSystemModel is a tree-level model, but still could use something like this QFileSystemModel Model hierarchical data in a tree in QListView. But only show data when the top level view shows, so little practical significance.

3.2, using the Model QFileSystemModel as QListView

Use QFileSystemModel as QListView the model is very simple, only three steps can be achieved:

  1. Objects created QFileSystemModel

  2. SetRootPath path to the directory corresponding to the file set QFileSystemModel

  3. SetModel to use a view (model) method to establish a connection model and view

3.3, the sample code

    def initDirModel(self):
        self.model = QtWidgets.QFileSystemModel()
        self.model.setRootPath(r"c:\temp")#监视目录异动
        self.listView.setModel(self.model)
        self.listView.setRootIndex(self.model.index(r"c:\temp"))()))#切换显示目录

Run shot:
Here Insert Picture Description

Four, QListView / QStandardItemModel

4.1 Overview

QStandardItemModel is a general Model Model / View architecture used to store custom data, it provides a classical approach based on the process model items, item type model must be QStandardItem class or subclass.

QStandardItemModel achieve QAbstractItemModel defined interface, which means that the model can be used to provide data view (eg QListView, QTableView and QTreeView, as well as your own custom view) any support for the interface. In order to achieve the performance and flexibility, the need for the subclass QAbstractItemModel model, to provide support for different types of data storage, e.g., QDirModel provide a model for the interface to the underlying file system.

4.2, using the Model QStandardItemModel as QListView

由于QStandardItemModel是一个通用的Model,使用它作为视图的Model实现起来比类似QFileSystemModel等便利化专用化的Model要稍微复杂,其复杂主要是数据初始化方面。具体实现步骤如下:

  1. 创建Model对象
    可以使用QStandardItemModel(parent: QObject = None)、QStandardItemModel(int rowCount, int columnCount, parent: QObject = None)来创建Model对象。

  2. 初始化数据
    初始化数据时,需要每个数据创建一个QStandardItem或其派生类的对象,并将其加入到Model中去。QStandardItem类有四个构造方法QStandardItem()、QStandardItem(str text)、QStandardItem(QIcon icon, str text)、QStandardItem(int rows, int columns = 1),分别用于创建单个空项、一个带数据的项、一个带图标和数据的项、多个空项,对于空项还需要使用setText(QVariant value, int role = Qt.UserRole + 1)等方法设置项存储的数据。

  3. 使用视图的setModel(model)方法将model和view建立连接

4.3、 一个完整的初始化方法代码及运行截图

    def initStandItemModel(self):
        self.model = QStandardItemModel()
        strList = ["item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10"]
        row = 0
        for itemStr in strList:
            item = StandardItem(itemStr)
            self.model.setItem(row, 0, item)
            row += 1
        self.listView.setModel(self.model)

运行截图:
Here Insert Picture Description

五、QListView与多列Model及使用QListView的modelColumn属性

5.1、概述

QListView的modelColumn属性用于控制视图中展现model中哪一列数据,缺省值为0,即展现第一列数据。

可以通过modelColumn()、setModelColumn(int column)来访问和设置该属性。但Qt Designer中该属性值只能为0,无法设置为非0,这是因为QListView只显示一列数据,一般情况下如果使用的Model没有多列数据的话,是无需设置modelColumn属性,但并不是不能使用多列数据的Model。如上面第三部分使用QFileSystemModel与QListView配合使用。

5.2、使用多列模式初始化

下面是一个使用QStandardItemModel创建的一个6行5列的Model与QListView配合使用的初始化代码:

    def initMultiColumnModel(self):
        self.model = QStandardItemModel()
        for row in range(6):
            for col in range(5):
                item = StandardItem("row: {row},col: {col}".format(row=row + 1, col=col + 1))
        self.listView.setModel(self.model)

如使用QFileSystemModel来测试,发现可以通过setModelColumn来调整显示的数据内容,然后又改成了QStandardItemModel,使用model的setItem方法来设置多列数据,也可以使用setModelColumn来调整显示数据。

5.3、多列模式动态调整显示数据列

多列模式的Model初始化后显示的是第一列数据,如果要调整显示其他列的数据,可以通过setModelColumn来调整显示列。

六、支持列表中展示图标的两种方法

在视图中的项不但可以展示文字,也可以展示图标和复选框,同时可以指定项是否可以拖拽、选择、编辑。有两种方法支持在项中展示图标。

6.1、使用QStandardItem(QIcon icon, str text)创建项

下面的代码支持将指定目录的图象文件的文件名和图象在视图中展示:

    def initIconModel(self):
        self.model = QStandardItemModel()

        ICon1 = QStandardItem(QIcon(r"F:\学习\python\资源\图像文件\add.png"),'add.png')
        ICon2 = QStandardItem(QIcon(r"F:\学习\python\资源\图像文件\application_windows_add.png"), 'application_windows_add.png')
        ICon3 = QStandardItem(QIcon(r"F:\学习\python\资源\图像文件\save.png"), 'save.png')
        ICon4 = QStandardItem(QIcon(r"F:\学习\python\资源\图像文件\search.png"), 'search.png')
        ICon5 = QStandardItem(QIcon(r"F:\学习\python\资源\图像文件\stop.gif"), 'stop.gif')

        self.model.appendRow(ICon1)
        self.model.appendRow(ICon2)
        self.model.appendRow(ICon3)
        self.model.appendRow(ICon4)
        self.model.appendRow(ICon5)
        self.listView.setModel(self.model)

运行后的界面初始化截图如下:
Here Insert Picture Description

6.2、使用QStandardItem()创建空项后通过setData指定图标文件为Qt.DecorationRole角色的数据

使用项的setData( QtCore.QVariant(icon), Qt.DecorationRole)方法,对应数据角色使用 Qt.DecorationRole。示例代码:

    def initIconModel(self):
        self.model = QStandardItemModel()
        ICon1 = QStandardItem('add.png')
        ICon1.setData(QtCore.QVariant(QIcon(r"F:\学习\python\资源\图像文件\add.png")),Qt.DecorationRole)
        ICon2 = QStandardItem('save.png')
        ICon2.setData(QtCore.QVariant(QIcon(r"F:\学习\python\资源\图像文件\save.png") ),Qt.DecorationRole)
        self.model.appendRow(ICon1)
        self.model.appendRow(ICon2)
        self.listView.setModel(self.model)

运行截图:
Here Insert Picture Description
其实还有个类似的方法,就是使用model的setData( QModelIndex,QtCore.QVariant(icon), Qt.DecorationRole)方法,当选择操作时要更改图标文件可以使用这种方法。只要在方法中获取到modelIndex就可以调用该方法。

七、支持获取变更数据的方法

在QListView视图中数据如果发生变化,可以通过QStandardItemModel的信号itemChanged连接一个自定义槽函数来获取变动的数据。
1、定义一个槽函数itemChanged

 def itemChanged(self,item):
        print(f"itemChanged,row={item.row()},column={item.column()}")

2、在构造方法中建立信号和槽的连接

self.model.itemChanged[QStandardItem ].connect(self.itemChanged)

这样只要触发了项的编辑就会发出该信号从而知道变动的数据项。

八、小结

本节通过案例详细介绍了QListView/Model编程的几个要点,包括QListView与不同model的配合步骤、多列Model中数据展示列的控制、给展示数据加上图标、获取变更数据项的方法等内容。

后记

另外老猿关于PyQt的付费专栏《使用PyQt开发图形界面Python应用》只需要9.9元,该部分与第十五章的内容基本对应,但同样内容在付费专栏上总体来说更详细、案例更多。本节内容在付费专栏的《第十八章、QListView/Model开发》。如果有兴趣也愿意支持老猿的读者,欢迎购买付费专栏。

最后感谢各位支持,你们的支持是我持续学习和更新的动力!

老猿Python,跟老猿学Python!

Published 581 original articles · won praise 3398 · Views 300,000 +

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/104071932