Qt model view framework: QDataWidgetMapper, QDataWidgetMapper, QStyledItemDelegate

QDataWidgetMapper

1. Description

QDataWidgetMapper can be used to map model data to widgets.

Every time the current index changes, each widget is updated with data from the model via the properties specified at mapping time. If the user edits the content of the widget, the same property is used to read the changes and write them back to the model. By default, each widget's user properties are used to transfer data between the model and the widget.

Item delegates can be set to support custom widgets. By default, the model is synchronized with the widget using a QItemDelegate.

Example: The following code maps a model's columns to widgets:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(model);
mapper->addMapping(mySpinBox, 0);
mapper->addMapping(myLineEdit, 1);
mapper->addMapping(myCountryChooser, 2);
mapper->toFirst();
  • QDataWidgetMapper supports two submission policies (enum QDataWidgetMapper::SubmitPolicy):
  • AutoSubmit: will update the model as soon as the current widget loses focus.
  • ManualSubmit: The model will not be updated unless submit() is called.

Also, other views showing the model are not updated until the user has made all modifications and committed them.

QDataWidgetMapper keeps track of external modifications. If the content of the model is updated in another module of the application, the widget will also be updated.

Two, attribute members

1、currentIndex : int

This property holds the current row or column.

If orientation is horizontal (the default), the widget will be populated with data from the index row, otherwise with data from the index column.

2、orientation : Qt::Orientation

This property holds the orientation of the model.

Changing the orientation clears any existing mappings.

3. Member functions

1、[信号] void currentIndexChanged(int index)

This signal is emitted after the current index has changed and all widgets have been populated with new data.

2、void revert()

Repopulates all widgets with the model's current data. All uncommitted changes will be lost.

3、void setCurrentModelIndex(const QModelIndex &index)

If orientation is horizontal (the default), sets the current index to the indexed row, otherwise to the indexed column.

Update all widgets with new data when the view's selection changes:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
connect(myTableView->selectionModel(), &QItemSelectionModel::currentRowChanged,mapper, &QDataWidgetMapper::setCurrentModelIndex);

4、bool submit()

Commits all changes from mapped widgets to the model. Returns true if all values ​​have been committed.

5、void toFirst()

If the orientation is horizontal, the widget is populated with data from the first row of the model, otherwise with data from the first column.

6、void toLast()

Populates the widget with data from the last row of the model if orientation is horizontal, otherwise uses data from the last column.

7、void toNext()

If the orientation is horizontal, the widget is populated with data from the next row of the model, otherwise with data from the next column.

8、void toPrevious()

If the orientation is horizontal, the widget is populated with data from the previous row of the model, otherwise with data from the previous column.

9、void addMapping(QWidget *widget, int section)

Add mappings between widgets and model parts. If the orientation is horizontal (the default), the section is a column in the model, otherwise a row.

For the following example, assume that the model myModel has two columns: the first column contains the names of the people in the group, and the second column contains their ages. First column is mapped to QLineEdit nameLineEdit and second column is mapped to QSpinBox ageSpinBox:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(myModel);
mapper->addMapping(nameLineEdit, 0);
mapper->addMapping(ageSpinBox, 1);

If a widget is already mapped to a section, the old mapping will be replaced by the new mapping.

Only one-to-one mapping between sections and widgets is allowed. It is not possible to map a single section to multiple widgets, or a single widget to multiple sections.

10、void clearMapping()

Clear all mappings.

11、int mappedSection(QWidget *widget) / QWidget *mappedWidgetAt(int section)

Returns the section the widget is mapped to, or -1 if the widget is not mapped. / Returns the mapped widget.

12、void removeMapping(QWidget *widget)

Remove the mapping for the widget.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

QDataWidgetMapper

1. Description

QDataWidgetMapper can be used to map model data to widgets.

Every time the current index changes, each widget is updated with data from the model via the properties specified at mapping time. If the user edits the content of the widget, the same property is used to read the changes and write them back to the model. By default, each widget's user properties are used to transfer data between the model and the widget.

Item delegates can be set to support custom widgets. By default, the model is synchronized with the widget using a QItemDelegate.

Example: The following code maps a model's columns to widgets:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(model);
mapper->addMapping(mySpinBox, 0);
mapper->addMapping(myLineEdit, 1);
mapper->addMapping(myCountryChooser, 2);
mapper->toFirst();
QDataWidgetMapper 支持两种提交策略(enum QDataWidgetMapper::SubmitPolicy):
AutoSubmit:将在当前小部件失去焦点后立即更新模型。
ManualSubmit:除非调用 submit(),否则不会更新模型。

Also, other views showing the model are not updated until the user has made all modifications and committed them.

QDataWidgetMapper keeps track of external modifications. If the content of the model is updated in another module of the application, the widget will also be updated.

Two, attribute members

1、currentIndex : int

This property holds the current row or column.

If orientation is horizontal (the default), the widget will be populated with data from the index row, otherwise with data from the index column.

2、orientation : Qt::Orientation

This property holds the orientation of the model.

Changing the orientation clears any existing mappings.

3. Member functions

1、[信号] void currentIndexChanged(int index)

This signal is emitted after the current index has changed and all widgets have been populated with new data.

2、void revert()

Repopulates all widgets with the model's current data. All uncommitted changes will be lost.

3、void setCurrentModelIndex(const QModelIndex &index)

If orientation is horizontal (the default), sets the current index to the indexed row, otherwise to the indexed column.

Update all widgets with new data when the view's selection changes:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
connect(myTableView->selectionModel(), &QItemSelectionModel::currentRowChanged,mapper, &QDataWidgetMapper::setCurrentModelIndex);

4、bool submit()

Commits all changes from mapped widgets to the model. Returns true if all values ​​have been committed.

5、void toFirst()

If the orientation is horizontal, the widget is populated with data from the first row of the model, otherwise with data from the first column.

6、void toLast()

Populates the widget with data from the last row of the model if orientation is horizontal, otherwise uses data from the last column.

7、void toNext()

If the orientation is horizontal, the widget is populated with data from the next row of the model, otherwise with data from the next column.

8、void toPrevious()

If the orientation is horizontal, the widget is populated with data from the previous row of the model, otherwise with data from the previous column.

9、void addMapping(QWidget *widget, int section)

Add mappings between widgets and model parts. If the orientation is horizontal (the default), the section is a column in the model, otherwise a row.

For the following example, assume that the model myModel has two columns: the first column contains the names of the people in the group, and the second column contains their ages. First column is mapped to QLineEdit nameLineEdit and second column is mapped to QSpinBox ageSpinBox:

QDataWidgetMapper *mapper = new QDataWidgetMapper;
mapper->setModel(myModel);
mapper->addMapping(nameLineEdit, 0);
mapper->addMapping(ageSpinBox, 1);

If a widget is already mapped to a section, the old mapping will be replaced by the new mapping.

Only one-to-one mapping between sections and widgets is allowed. It is not possible to map a single section to multiple widgets, or a single widget to multiple sections.

10、void clearMapping()

Clear all mappings.

11、int mappedSection(QWidget *widget) / QWidget *mappedWidgetAt(int section)

Returns the section the widget is mapped to, or -1 if the widget is not mapped. / Returns the mapped widget.

12、void removeMapping(QWidget *widget)

Remove the mapping for the widget.

QStyledItemDelegate

1. Description

Individual items are drawn by delegates when displaying data from the model in a Qt item view. Additionally, when an item is being edited, it provides an editor widget that is placed on top of the item view while editing. QStyledItemDelegate is the default delegate for all Qt item views and is installed on them when they are created.

Data for items in the model are assigned an ItemDataRole. Items can store a QVariant for each character. QStyledItemDelegate implements the display and editing of the most common data types that users expect, including booleans, integers, and strings.

Data will plot differently depending on their role in the model. Here are the roles and data types that delegates can handle for each role:

  • Qt::BackgroundRole:QBrush
  • Qt::CheckStateRole:Qt::CheckState
  • Qt::DecorationRole:QIcon、QPixmap、QImage、QColor
  • Qt::DisplayRole: QString and types with string representation
  • Qt::EditRole: see QItemEditorFactory for details
  • Qt::FontRole:QFont
  • Qt::SizeHintRole:QSize
  • Qt::TextAlignmentRole:Qt::Alignment
  • Qt::ForegroundRole:QBrush

Subclassing QStyledItemDelegate

If the delegate does not support the required data type for drawing, or you want to customize the drawing of items, you need to subclass QStyledItemDelegate and reimplement paint() and sizeHint(). The paint() function is called individually for each item, and a hint can be specified for each item using sizeHint().

A custom delegate can provide an editor without using an editor item factory. In this case, the following virtual functions must be reimplemented:

  • createEditor(): Returns a widget for changing model data, and can be reimplemented to customize editing behavior.
  • setEditorData(): Provides the widget with data to operate on.
  • updateEditorGeometry(): Ensures that the editor is displayed correctly relative to the project view.
  • setModelData(): Return updated data to the model.
  • QStyledItemDelegate and QItemDelegate

The difference between these two classes is that QStyledItemDelegate implements the paint() function. Unless custom item display is required, it is recommended to use QStyledItemDelegate as the base class when implementing custom delegates or using Qt style sheets.

2. Member functions

1、QWidget * createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index)

Reimplement: QAbstractItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const.

Returns the widget for editing the item specified by index for editing. The parent widget and style options are used to control how the editor widget is displayed. (Set qss/Style to be set on the parent widget)

2、QString displayText(const QVariant &value, const QLocale &locale)

This function returns the string of the Qt::DisplayRole that the delegate will use to display the model in the locale. value is the value of the Qt::DisplayRole provided by the model.

The default implementation uses QLocale::toString to convert the value to a QString.

For empty model indices, ie indices where the model returns an invalid QVariant, this function is not called.

3、bool eventFilter(QObject *editor, QEvent *event)

Returns true if the editor is a valid QWidget and the event was processed, false otherwise.

The following key events are handled by default:

  • Tab
  • Backtab
  • Enter
  • Return
  • Esc

If the editor type is QTextEdit or QPlainTextEdit, the Enter and Return keys are not processed.

In the case of Tab, Backtab, Enter, Return key press events, the editor's data is submitted to the model and the editor is closed.

  • If the event is pressing the Tab key, the view will open the editor on the next item in the view.
  • If the event is a Backtab key, the view will open the editor for the previous item in the view.
  • If the event is an Esc key press, the editor will close without committing its data.

4、void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index)

Initialize the option with the value of the index index.

This method is useful when subclasses need a QStyleOptionViewItem, but don't want to set all the information themselves.

5、void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)

Reimplemented: QAbstractItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const.

When reimplementing paint() in a subclass. Use initStyleOption() to set options in the same way as QStyledItemDelegate.

Use options when drawing whenever possible. Specifically its rect variable to determine where to draw and its state to determine if it is enabled or selected.

After drawing, you should ensure that the painter returns to the state provided when calling this function (call QPainter::save() before painting and QPainter::restore() after).

6、void setEditorData(QWidget *editor, const QModelIndex &index)

Reimplemented: QAbstractItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const.

Sets the data to be displayed and edited by the editor from the data model item specified by the model index.

The default implementation stores the data in the user property of the editor widget.

7、void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index)

Reimplemented: QAbstractItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const.

Fetches data from the editor widget and stores it in the specified model at the item index.

The default implementation gets the value to be stored in the data model from the editor widget's user property.

8、QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index)

Reimplemented: QAbstractItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const.

Returns the size required by the delegate to display the item specified by index, taking into account style information provided by options.

 

9、void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index)

Reimplemented: QAbstractItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const.

Updates the editor for the item specified by index according to option.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Original link: https://blog.csdn.net/kenfan1647/article/details/119821384

Guess you like

Origin blog.csdn.net/hw5230/article/details/131942785