Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Six consecutive shocks of QT Model/View

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Qt Model/View Learning Notes (1)

Introduction

Qt 4 introduces a new set of item view classes that use model/view structures to manage the relationship between data and the presentation layer. Brought by this structure.

Functional separation gives developers more flexibility to customize the presentation of data items, and it also provides a standard model interface to make more

Data sources can be used by these item view. The structure of model/view is described here, and each component in the structure is explained.

Some examples are given to illustrate how these classes are used.

Model/View structure

Model-View-Controller (MVC), a design pattern developed from Smalltalk, is often used to build user interfaces. Works on classic design patterns are described as follows:

MVC consists of three kinds of objects. Model is the application object, View is its on-screen representation, and Controller defines how the user interface responds to user input. Before MVC, user interface design tended to combine the three, and MVC decoupled them to improve flexibility and reusability.

If you combine view with controller, the result is a model/view structure. This structure still separates data storage from data representation, and it is based on the same idea as MVC, but it is simpler. This separation makes it possible to display the same data on several different view, and a new view can be reimplemented without having to change the underlying data structure. In order to deal with user input more flexibly, the concept of delegate is introduced. Its advantage is that the rendering and programming of data items can be customized.

As shown in the figure above, model communicates with the data source and provides an interface for other components in the structure to use. The nature of communication depends on the type of data source.

And model implementation. View gets the model indexes from model, which is a reference to the data item. You can get data from a data source by providing model indexes to model,view.

In standard views, delegate renders data items, and when a data item is selected, delegate communicates directly with model through model indexes. In general, model/view-related classes can be divided into the three groups mentioned above: models,views,delegates. These components are defined by abstract classes, they provide a common interface and, in some cases, default implementations. Abstract classes mean that subclassing is required to provide complete functionality that other components want. This also allows you to implement custom components. Models,views,delegates communicate with each other through signal and slot mechanism:

A signal from model informs view that the data in the data source has changed.

A signal from the view provides information about the interaction between the displayed data item and the user.

The signal that occurs from the delegate is used to inform model and view about the status of the current editor when editing.

Models

All item models are based on the QAbstractItemModel class, which defines the interface for views and delegates to access data.

The data itself does not have to be stored in model, it can be placed in a data structure or in another class, file, database, or other program component.

The basic concepts of model are described in the Model Classes section.

QAbstractItemModel provides an interface to the data, which is very flexible and basically meets the needs of views, regardless of whether the data is in any of the following forms

Performance, such as tables,lists,trees. However, when you re-implement a model, if it is based on data structures in the form of table or list, it is best to start with QAbstractListModel,QAbstractTableModel, as they provide the appropriate default implementation of general functions. These classes can be subclassed to support special customization requirements. The process of subclassing model is discussed in the Create New Model section

QT provides some off-the-shelf models for processing data items:

QStringListModel is used to store simple QString lists.

QStandardItemModel manages complex tree-structured data items, each of which can contain arbitrary data.

QDirModel provides file and directory information in the local file system.

QSqlQueryModel, QSqlTableModel,QSqlRelationTableModel is used to access the database.

If these standard Model do not meet your needs, you should subclass QAbstractItemModel,QAbstractListModel or

QAbstractTableModel to customize.

Views

Different view have fully realized their own functions: QListView displays the data as a list, QTableView displays the data in Model in the form of table, and QTreeView displays the data in model with a hierarchical list. These classes are based on QAbstractItemView abstract base classes, and although these classes are off-the-shelf and fully implemented, they can be used for subclassing to meet custom requirements.

Delegates

QAbstractItemDelegate is the abstract base class for delegate in the model/view architecture. The default delegate implementation is provided in the QItemDelegate class. It can be used for the default delegate of the Qt standard views.

Sort

In the model/view architecture, there are two ways to sort, and which one depends on your underlying Model.

If your model is sortable, that is, it reimplements the QAbstractItemModel::sort () function, both QTableView and QTreeView provide API, which allows you to sort Model data programmatically. Alternatively, you can sort interactively (for example, by allowing users to sort data by clicking on the view header). You can do this: connect the QHeaderView::sectionClicked () signal to the QTableView::sortByColum () slot or the QTreeView::sortByColumn () slot.

Alternatively, if your model does not provide the required interface or you want to represent data in list view, you can use a proxy

Model transforms your model data structure before representing data in view.

Convenience class

Many convenience classes are derived from the standard view classes, which facilitate those who use item-based view and table classes in Qt, and they should not be subclassed

They simply provide a familiar interface to the equivalent class of Qt 3. These classes are QListWidget,QTreeWidget,QTableWidget, which provide similar behavior like QListBox and QlistView,QTable in Qt 3. These analogies View classes are inflexible and cannot be used for arbitrary models, and the use of model/view methods for data processing is recommended.

Qt Model/View Learning Notes (2)

Introduction

Qt provides two standard models:QStandardItemModel and QDirModel. QStandardItemModel is a versatile

Model, which can be used to represent the different data structures required by list,table,tree views. This model also holds data. QDirModel

Maintains information about the contents of the directory, which does not hold the data itself, but only describes the files and directories in the local file system.

QDirModel is an off-the-shelf model that can be easily configured for existing data. Using this model, you can well demonstrate how to

Set model for a ready-made view to study how to use model indexes to manipulate data.

Collocation of model and views

QListView and QTreeView go well with QDirModel. The following example shows the same information in tree view as in list view, where QDirModel provides directory content data. The two Views share user selections, so each selected item is highlighted in each view.

First assemble a QDirModel for use, and then create a views to display the contents of the directory. This shows me the easiest way to use model.

The creation and use of model is done in the main () function:

Int main (int argc, char * argv [])

{

QApplication app (argc, argv)

QSplitter * splitter = new QSplitter

QDirModel * model = new QDirModel

/ / create data from the default directory

QTreeView * tree = new QTreeView (splitter)

Tree- > setModel (model)

Tree- > setRootIndex (model- > index (QDir::currentPath ()

QListView * list = new QListView (splitter)

List- > setModel (model)

List- > setRootIndex (model- > index (QDir::currentPath ()

/ / configure a view to display the data in model by simply calling setModel () and passing the directory model as a parameter

/ / setRootIndex () tells views which directory to display, which requires providing a model index, and then using this

/ / model index goes to model to get data

The function / / index () is unique to QDirModel. By taking a directory as an argument, you get the required model index.

/ / the other code is just a window to show and enter the event loop of the program.

Splitter- > setWindowTitle ("Two views onto the same directory model")

Splitter- > show ()

Return app.exec ()

}

Qt Model/View Learning Notes (3)

Model class

Basic concept

In the model/view architecture, model provides a standard interface for view and delegates usage data. In Qt, the standard interface QAbstractItemModel class is defined. Regardless of the underlying data structure in which the data is stored, the subclasses of QAabstractItemModel represent the data in a hierarchical structure that contains tables of data items. We follow this convention to access data items in model, but this convention does not have any restrictions on how the data is displayed. When the data changes, the model notifies the associated views through the signal slot mechanism.

Model Indexes

In order to separate data storage from data access, the concept of model index is introduced. With model index, you can reference data items in model, and both Views and delegates use indexes to access the data items and then display them. Therefore, only model needs to know how to get the data, and the data types managed by model can be very widely defined. Model indexes contains a pointer to the model that created them, which avoids confusion when working with multiple model.

QAbstractItemModel * model = index.model ()

Model indexes provides a temporary reference to a piece of data information through which you can access or modify data in model. Since model sometimes reorganizes internal data structures, model indexes becomes invalid, so temporary model indexes should not be saved. If you need a long-term reference to data information, you should create a persistent model index. This reference will be updated. Temporary model indexes is provided by QModelIndex, while persistent model indexes is provided by QPersistentModelIndex. When getting the model index of a data item, you need to consider three attributes about model: the number of rows, the number of columns, and the model index of the parent item.

Rows and columns

In the most basic form, an model can be accessed as a simple table, with each data item located by the number of rows and columns. That doesn't mean

The underlying data is stored in an array structure. The use of rows and columns is just a convention that allows components to communicate with each other. You can specify

If you get any item of data by the number of rows in model, you can get the index that corresponds to the data item one by one.

QModelIndex index = model- > index (row, column,...)

Model provides interfaces for simple, single-level data structures such as list and tables, which, as shown in the code above, no longer require additional information to be provided. When we are getting a model index, we need to provide additional information.

The image above represents a basic table model, each of which is located by a pair of rows and rows. Through the number of rows and rows, you can get the model index that represents a data item.

QModelIndex indexA = model- > index (0,0, QModelIndex ())

QModelIndex indexB = model- > index (1,1, QModelIndex ())

QModelIndex indexC = model- > index (2,1, QModelIndex ())

The top-level items of a model, taken by QModelIndex (), are used as parents.

Parent item

Table-like interfaces are ideal when used with table or list view, and this row-and-row system exactly matches the way view is displayed.

However, structures like tree views require model to provide a more flexible interface to access data items. Each data item may belong to another item

Parent item, the superior item can get a list of subordinate items.

When getting the index of a data item in model, we must specify information about the parent of the data item. Outside of model, reference a data

The only way to get an item is through model index, so you need to specify the information for the parent when you get the model index.

QModelIndex index = model- > index (row, column, parent)

In the figure above, items An and C are siblings at the top level in model:

QModelIndex indexA = model- > index (0,0, QModelIndex ())

QModelIndex indexC = model- > index (2,1, QModelIndex ())

A has many children, and one of its children, B, gets it with the following code:

QModelIndex indexB = model- > index (1,0, indexA)

Item role

Items in model can be used as various roles, which allows different data to be provided for different environments. For example, Qt::DisplayRole is used to access a string that is displayed as text in view. Typically, each data item can provide data for many different roles, and standard roles are defined in Qt::ItemDataRole. We can get the data we need by specifying the model index and role:

QVariant value = model- > data (index, role)

The role indicates which type of data is referenced from the model. Views can display roles in different forms, so provide correct information for each role

The information is very important. By providing appropriate data for each role, model also provides hints for views and delegates on how to correctly

Show these data items to the user. Different views can freely parse or ignore these data information, and for special occasions, you can also define

Some additional roles.

Summary of concepts:

1Magical Model indexes provides views and delegages with information about the location of data items in model, which has nothing to do with the underlying data structure.

2, reference the data item by specifying the number of rows, columns, and the model index of the parent item.

3. According to the requirements of other components, model indexes is built by model.

4. When using index (), if you specify a valid parent's model index, the returned model index corresponds to a child of the parent.

5. When using index (), if you specify the model index of an invalid parent, the returned model index corresponds to a child of the top-level item.

6. Roles distinguish between different types of data contained in a data item.

Use Model Indexes

QDirModel * model = new QDirModel

QModelIndex parentIndex = model- > index (QDir::currentPath ())

Int numRows = model- > rowCount (parentIndex)

For (int row = 0; row)

< numRows; ++row) { QModelIndex index = model->

Index (row, 0, parentIndex)

Tring text = model- > data (index, Qt::DisplayRole). ToString ()

/ / Display the text in a widget.

}

The above example illustrates the basic principles of getting data from model:

1the dimensions of the rowCount model can be obtained from rowCount () and columnCount (). These functions usually require a model index that represents the parent.

2Magical model indexes is used to access data items from model, and the data items are located by row, column and parent model index.

3, in order to access the model top-level items, you can use QModelIndex () to specify.

4. Data items provide different data for different roles. In order to get the data, you have to specify a role in addition to model index.

Qt Model/View Learning Notes (4)

Create a new Models

Introduction

The functional separation between model/view components allows the creation of model to take advantage of off-the-shelf views. It can also use standard functional graphical user interface components such as QListView,QTableView and QTreeView to display data from various data sources.

The QAbstractListModel class provides a very flexible interface that allows data sources to manage information in a hierarchical form, as well as some kind of

The way to insert, delete, modify and store data. It also provides support for drag and drop operations.

QAbstractListModel and QAbstractTableModel provide interfaces for simple, non-hierarchical data, which is a good starting point for simpler list and table models.

Design a Model

When we create a new model for an existing data structure, the first consideration is which model should be chosen to interface the data.

If the data structure can be represented by a list or table of data items, consider subclassing QAbstractListModel or QAbstractTableModel

Now that these classes reasonably provide default implementations for many functions

However, if the underlying data structure can only be represented as a hierarchical tree structure, then a subclassed QAbstractItemModel must be obtained.

Regardless of the form of the underlying data structure, it is always a good idea to implement a standard QAbstractItemModel API in a particular model, which makes it possible to access the underlying data structure in a more natural way. This also makes it easier to build model with data, and other

The model/view component of can also interact with it using standard API.

An example of a read-only model

This example implements a simple, non-hierarchical, read-only data model based on the QStringistModel class. It has a QStringList as its internal data source and implements only a few necessary interfaces. For simplicity, it subclasses QAbstractListModel, a base class that provides reasonable default behavior and provides a simpler interface than QAbstractItemModel. When we implement a model, don't forget that QAbstractItemModel itself does not store any data, it only provides views access

The interface for data.

Class StringListModel: public QAbstractListModel

{

Q_OBJECT

Public:

StringListModel (const QStringList & strings, QObject * parent = 0)

: QAbstractListModel (parent), stringList (strings) {}

Int rowCount (const QModelIndex & parent = QModelIndex ()) const

QVariant data (const QModelIndex & index, int role) const

QVariant headerData (int section, Qt::Orientation orientation

Int role = Qt::DisplayRole) const

Private:

QStringList stringList

}

In addition to the constructor, we only need to implement two functions: rowCount () returns the number of rows in model, and data () returns data items corresponding to a particular model index. A well-behaved model also implements headerData (), which returns the data that tree and table views need to display in the title.

Because this is a non-hierarchical model, we do not have to consider the parent-child relationship. If model has a hierarchical structure, we should also implement the index () and parent () functions.

The size of the Model

We believe that the number of rows in model is the same as the number of string in string list:

Int StringListModel::rowCount (const QModelIndex & parent) const

{

Return stringList.count ()

}

By default, model derived from QAbstractListModel has only one column, so you don't need to implement columnCount ().

Model title and data

QVariant StringListModel::data (const QModelIndex & index, int role) const

{

If (! index.isValid ()

Return QVariant ()

If (index.row () > = stringList.size ())

Return QVariant ()

If (role = = Qt::DisplayRole)

Return stringList.at (index.row ())

Else

Return QVariant ()

}

QVariant StringListModel::headerData (int section, Qt::Orientation orientation

Int role) const

{

If (role! = Qt::DisplayRole)

Return QVariant ()

If (orientation = = Qt::Horizontal)

Return QString ("Column 1") .arg (section)

Else

Return QString ("Row 1") .arg (section)

}

A data item may have multiple roles and output different data according to different roles. In the above example, the data item in model has only one role

DisplayRole, however, we can also reuse the data provided to DisplayRole for other roles, such as we can use it as ToolTipRole.

Editable model

Above we demonstrated a read-only model that is only used to show users that editable list model may be more useful for many programs. We only need to provide the implementation of the other two functions flags () and setData () for the read-only model. The following function declarations are added to the class definition:

Qt::ItemFlags flags (const QModelIndex & index) const

Bool setData (const QModelIndex & index, const QVariant & value)

Int role = Qt::EditRole)

Make model editable

Delegate checks whether the data item is editable before creating the editor. Model must let delegate know that its data items are available.

Edited. This can be achieved by returning a correct tag for each data item, and in this case, we assume that all data items are

Editable and selectable:

Qt::ItemFlags StringListModel::flags (const QModelIndex & index) const

{

If (! index.isValid ()

Return Qt::ItemIsEnabled

Return QAbstractItemModel::flags (index) | Qt::ItemIsEditable

}

We don't need to know how delegate performs the actual editing process, we just need to provide delegate with a method that delegate uses to set up the data in model. This special function is setData ():

Bool StringListModel::setData (const QModelIndex & index)

Const QVariant & value, int role)

{

If (index.isValid () & & role = = Qt::EditRole) {

StringList.replace (index.row (), value.toString ())

Emit dataChanged (index, index)

Return true

}

Return false

}

When the data is set, model must let views know that some data has changed, which can be done by emitting a dataChanged () signal.

Because only one data item has changed, the range of variation indicated in the signal is limited to one model index.

Insert, delete row

It is possible to change the number of rows and columns in model. Of course, in this column, we only consider the case of rows, we just need to re-implement insert and delete

The following should be declared in the class definition

Bool insertRows (int position, int rows, const QModelIndex & index = QModelIndex ())

Bool removeRows (int position, int rows, const QModelIndex & index = QModelIndex ())

Since each row in the model corresponds to a string in the list, the insertRows () function inserts an empty string at the specified location in the string list

The parent index is usually used to determine the location of the rows and rows in the model. In this case, there is only a single top-level item, so you only need to insert an empty string in the list.

Bool StringListModel::insertRows (int position, int rows, const QModelIndex & parent)

{

BeginInsertRows (QModelIndex (), position, position+rows-1)

For (int row = 0; row)

< rows; ++row) { stringList.insert(position, ""); } endInsertRows(); return true; } beginInsertRows()通知其他组件行数将会改变。endInsertRows()对操作进行确认与通知。 返回true表示成功。 删除操作与插入操作类似: bool StringListModel::removeRows(int position, int rows, const QModelIndex &parent) { beginRemoveRows(QModelIndex(), position, position+rows-1); for (int row = 0; row < rows; ++row) { stringList.removeAt(position); } endRemoveRows(); return true; } Qt Model/View 学习笔记 (五) View 类 概念 在model/view架构中,view从model中获得数据项然后显示给用户。数据显示的方式不必与model提供的表示方式相同,可以与底层存储数据项的数据结构完全不同。 内容与显式的分离是通过由QAbstractItemModel提供的标准模型接口,由QAsbstractItemview提供的标准视图接口共同实现的。普遍使用model index来表示数据项。view负责管理从model中读取的数据的外观布局。 它们自己可以去渲染每个数据项,也可以利用delegate来既处理渲染又进行编辑。 除了显示数据,views也处理数据项的导航,参与有关于数据项选择的部分功能。view也实现一些基本的用户接口特性,如上下文菜单与拖拽功能。view也为数据项提供了缺省的编程功能,也可搭配delegate实现更为特殊的定制编辑的需求。 一个view创建时必不需要model,但在它能显示一些真正有用的信息之前,必须提供一个model。view通过使用 selections来跟踪用户选择的数据项。每个view可以维护单独使用的selections,也可以在多个views之间共享。有些views,如QTableView和QTreeView,除数据项之外也可显示标题(Headers),标题部分通过一个view来实现,QHeaderView。标题与view一样总是从相同的model中获取数据。从 model中获取数据的函数是QabstractItemModel::headerDate(),一般总是以表单的形式中显示标题信息。可以从QHeaderView子类化,以实现更为复杂的定制化需求。 使用现成的view Qt提供了三个现成的view 类,它们能够以用户熟悉的方式显示model中的数据。QListView把model中的数据项以一个简单的列表的形式显示,或是以经典的图标视图的形式显示。QTreeView把model中的数据项作为具有层次结构的列表的形式显示,它允许以紧凑的深度嵌套的结构进行显示。QTableView却是把model中的数据项以表格的形式展现,更像是一个电子表格应用程序的外观布局。 以上这些标准view的行为足以应付大多数的应用程序,它们也提供了一些基本的编辑功能,也可以定制特殊的需求。 使用model 以前的例子中创建过一个string list model,可以给它设置一些数据,再创建一个view把model中的内容展示出来: int main(int argc, char *argv[]) { QApplication app(argc, argv); // Unindented for quoting purposes: QStringList numbers; numbers setSelectionModel(firstTableView->

SelectionModel ()

Now all views operate on the same selection model, and the data is synchronized with the selections.

In the above example, the two view types are the same. If the two view types are different, then the selected data item is in each view.

The forms of expression in will be very different. For example, a contiguous selection in a table view and a representation in a tree view

It may be a combination of several highlighted pieces of data items.

Qt Model/View Learning Notes (6)

Select a data item in views

Concept

The selection model used in the new view class is much better than the model in Qt3. It provides a more comprehensive description of the choice of model/view-based architecture. Although the standard classes responsible for manipulating selections are sufficient for the provided views, you can also create specific selection models to meet your specific needs.

Information about the data items selected in view is kept in an instance of the QItemSelectionModel class. It also maintains model indexes information for data items in each separate model, which is associated with any views. Since a single model can be used for multiple views, it is also possible to share selection information among multiple views, which allows multiple views to be displayed in a consistent manner.

The selection consists of multiple selection ranges. The range of choices is maximized by recording only the start model indexes and the end model indexes. Discontinuous selection data items are described by a plurality of selection ranges. Select a collection of model records model indexes to describe a selection. The most recently selected data item is called current selection. The application can modify the effect of the selection by using some type of selection command.

When making a selection operation, you can think of QItemSelectionModel as a record of the selection status of all data items in the model. Once a selection model is established, the collection of all items can be selected, unselected, or selected states can be switched without knowing which data items have been selected. The indexes of all selected items is available at any time, and other components can be notified of changes through the signal slot mechanism.

Use the selection model

The standard view class provides a default selection model that can be used in large-number programs. The selection model in a view can be obtained by calling view's function selectionModel (), or the selection model can be shared among multiple views through setSelectionModel (), so generally speaking, it is not necessary to build a new model.

You can create a selection by assigning a model and a pair of model indexes to QItemSelection. The use of indexes depends on a given model, and these two indexes are interpreted as the upper-left and lower-right items in the selected block. The selection of items in model is subject to the selection model.

Select item

Build a table model with 32 items that are displayed with a table view:

TableModel * model = new TableModel (8, 4, & app)

QTableView * table = new QTableView (0)

Table- > setModel (model)

QItemSelectionModel * selectionModel = table- > selectionModel ()

QModelIndex topLeft

QModelIndex bottomRight

TopLeft = model- > index (0,0, QModelIndex ())

BottomRight = model- > index (5,2, QModelIndex ())

QItemSelection selection (topLeft, bottomRight)

SelectionModel- > select (selection, QItemSelectionModel::Select)

The results are as follows:

Read selection statu

The indexes stored in the selection model can be read with the selectionIndexes () function. It returns an unsorted list of model indexes that we can traverse if we know which model they are associated with.

QModelIndexList indexes = selectionModel- > selectedIndexes ()

QModelIndex index

Foreach (index, indexes) {

QString text = QString ("(% 1jue% 2)") .arg (index.row ()) .arg (index.column ())

Model- > setData (index, text)

}

The selection model signals when the selection changes. This is used to inform other components of changes that have taken place between the overall and current focus items. We can connect the selectionChanged () signal to a slot to check which items are selected or deselected when the signal is generated. This slot is called with two parameters, both of which are QItemSelection objects, one containing the newly selected item and the other containing the newly deselected item. The following code demonstrates adding data content to a newly selected item and emptying the contents of the newly deselected item.

Void MainWindow::updateSelection (const QItemSelection & selected)

Const QItemSelection & deselected)

{

QModelIndex index

QModelIndexList items = selected.indexes ()

Foreach (index, items) {

QString text = QString ("(% 1jue% 2)") .arg (index.row ()) .arg (index.column ())

Model- > setData (index, text)

}

Items = deselected.indexes ()

Foreach (index, items)

Model- > setData (index, "")

}

You can also track the current focus item by responding to the currentChanged () signal. The corresponding slot has two receive parameters, one for the previous focus and the other for the current focus.

Void MainWindow::changeCurrent (const QModelIndex & current)

Const QModelIndex & previous)

{

StatusBar ()-> showMessage (

Tr ("Moved from (% 1m% 2) to (% 3m% 4)")

.arg (previous.row ()) .arg (previous.column ())

.arg (current.row ()) .arg (current.column ()

}

Update selection

The selection instruction is provided through the selection flag, which is defined in the QItemSelectionModel::SelectionFlag. Select tags, Toggle tags, Deselect tags, Current tags and Clear tags are commonly used, and their meaning is clear at a glance. Execute the following code along the results of the above example:

QItemSelection toggleSelection

TopLeft = model- > index (2,1, QModelIndex ())

BottomRight = model- > index (7,3, QModelIndex ())

ToggleSelection.select (topLeft, bottomRight)

SelectionModel- > select (toggleSelection, QItemSelectionModel::Toggle)

The results are as follows:

By default, the selection instruction is only for a single item (specified by model indexes). However, the selection instruction can change the entire row and column by combining it with another tag. For example, if you use only one index to call select (), but use the combination of the Select tag and the Rows tag, then the entire line including that item will be selected. Look at the following example:

QItemSelection columnSelection

TopLeft = model- > index (0,1, QModelIndex ())

BottomRight = model- > index (0,2, QModelIndex ())

ColumnSelection.select (topLeft, bottomRight)

SelectionModel- > select (columnSelection

QItemSelectionModel::Select | QItemSelectionModel::Columns)

QItemSelection rowSelection

TopLeft = model- > index (0,0, QModelIndex ())

BottomRight = model- > index (1,0, QModelIndex ())

RowSelection.select (topLeft, bottomRight)

SelectionModel- > select (rowSelection

QItemSelectionModel::Select | QItemSelectionModel::Rows)

The results are as follows

Select all items in the model

In order to select all items in model, you must first create a selection that includes all items at the current level:

QModelIndex topLeft = model- > index (0,0, parent)

QModelIndex bottomRight = model- > index (model- > rowCount (parent)-1

Model- > columnCount (parent)-1, parent)

QItemSelection selection (topLeft, bottomRight)

SelectionModel- > select (selection, QItemSelectionModel::Select)

The top-level index can be as follows:

QModelIndex parent = QModelIndex ()

For a hierarchical model, you can use the hasChildren () function to determine whether a given item is the parent of another item.

Qt Model/View Learning Notes (7) Qt Model/View Learning Notes 2010-06-28 12:29:10 read 28 comments 0 size: large, medium and small subscriptions

Qt Model/View study notes

Delegate class

Concept

Unlike the MVC pattern, the model/view structure does not have completely independent components for interacting with users. Generally speaking, view is responsible for displaying the data

To the user, but also to process the user's input. In order to achieve more spirituality, the interaction is performed through delegagte. It provides input functions and is responsible for rendering each data item in the view. The standard interface for controlling delegates is defined in the QAbstractItemDelegate class. Delegates renders the content by implementing paint () and sizeHint (). However, a simple widget-based delegates can be subclassed from QItemDelegate instead of QAbstractItemDelegate, so that you can use the default implementation of the above functions it provides. Delegate can use widget to handle the editing process, or it can handle events directly.

Use off-the-shelf delegate

The standard views provided by Qt uses an instance of QItemDelegate to provide editing capabilities. It renders data items for each standard view in a normal style. These standard views include: QListView,QTableView,QTreeView. All standard roles are handled through the default delegate included in the standard views. The delegate used by a view can be obtained using the itemDelegate () function, while the setItemDelegate () function can install a custom delegate.

A simple delegate

This delegate uses QSpinBox to provide editing capabilities. It is mainly intended to be used on models that displays integers. Although we have established an integer-based table model, we can also use QStandardItemModel because delegate can control data entry. We have created another table view to display the content of the model and edit it with our custom delegate.

We subclass from QItemDelegate so that we can take advantage of its default implementation of the display function. Of course, we must provide functions to manage the widget for editing:

Class SpinBoxDelegate: public QItemDelegate

{

Q_OBJECT

Public:

SpinBoxDelegate (QObject * parent = 0)

QWidget * createEditor (QWidget * parent, const QStyleOptionViewItem & option)

Const QModelIndex & index) const

Void setEditorData (QWidget * editor, const QModelIndex & index) const

Void setModelData (QWidget * editor, QAbstractItemModel * model

Const QModelIndex & index) const

Void updateEditorGeometry (QWidget * editor

Const QStyleOptionViewItem & option, const QModelIndex & index) const

}

It is important to note that when a delegate is created, there is no need to install a widget, and the widget for editing is created only when it is really needed.

Provide editor

In this example, when table view needs to provide an editor, it asks delegate to provide a widget that can be used for editing, which should apply to the data item that is currently being modified. This is exactly what the createEditor () function should do:

QWidget * SpinBoxDelegate::createEditor (QWidget * parent

Const QStyleOptionViewItem & / * option * /

Const QModelIndex & / * index * /) const

{

QSpinBox * editor = new QSpinBox (parent)

Editor- > setMinimum (0)

Editor- > setMaximum

Return editor

}

We don't need to track the pointer to the widget, because view destroys the widget when it's not needed. We have also installed the delegate default event filter for editors, which provides the standard editing shortcuts that users expect. View ensures that the data and geometric layout of the editor are set correctly by defining the corresponding functions. We can also create different editors according to different model index. For example, we have a column of integers and a column of strings, and we can create a QSpinBox or QLineEdit based on which column is edited. Delegate must provide a function to copy the data from model into the editor.

Void SpinBoxDelegate::setEditorData (QWidget * editor

Const QModelIndex & index) const

{

Int value = index.model ()-> data (index, Qt::DisplayRole). ToInt ()

QSpinBox * spinBox = static_cast (editor)

SpinBox- > setValue (value)

}

Submit data to model

This requires us to implement another function, setModelData ():

Void SpinBoxDelegate::setModelData (QWidget * editor, QAbstractItemModel * model

Const QModelIndex & index) const

{

QSpinBox * spinBox = static_cast (editor)

SpinBox- > interpretText ()

Int value = spinBox- > value ()

Model- > setData (index, value)

}

The standard QItemDelegate class emits a closeEditor () signal to notify view when it finishes editing. View ensures that the editor widget is closed and destroyed. In this case, we only provide a simple editing function, so there is no need to send a signal.

Update editor geometric layout

Delegate is responsible for managing the geometric layout of the editor. This geometric layout information is created when editing or when the size and position of the view is changed.

Should be provided. Fortunately, view can provide this necessary information through a view option.

Void SpinBoxDelegate::updateEditorGeometry (QWidget * editor

Const QStyleOptionViewItem & option, const QModelIndex & / * index * /) const

{

Editor- > setGeometry (option.rect)

}

Edit Tip

After editing, delegate will provide other components with hints about the editing results, as well as hints for subsequent editing operations.

This can be done by emitting a closeEditor () signal with some kind of hint. These signals are captured by the default QItemDelegate event filter installed on spin box. For this default event filtering, when the user presses enter, delegate commits the data in model and closes spin box.

We can install our own event filters to meet our needs, for example, we can launch a

CloseEditor () signal to automatically start editing the next item in the view.

If ($! = jQuery) {$= jQuery.noConflict ();}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report