Qt model view framework: QHeaderView, QItemEditorFactory, QItemDelegate

QHeaderView

1. Description

QHeaderView displays the header used in item views such as QTableView, QTreeView.

The header uses the QAbstractItemModel::headerData() function to get the data for each part from the model. Data can be set using QAbstractItemModel::setHeaderData().

For horizontal headings, this section corresponds to a column in the model, and for vertical headings, this section corresponds to a row in the model.

move title section

Headings can be fixed in place or moved using setSectionsMovable(). It can be made clickable via setSectionsClickable() and has resize behavior according to setSectionResizeMode().

Exterior

QTableWidget and QTableView create default headers. If you want the title to be visible, call setVisible().

Not all ItemDataRoles will affect QHeaderView. If you need to draw other characters, you can inherit QHeaderView and reimplement paintEvent(). The following item data roles are available to QHeaderView, unless they conflict with styles (this can happen in styles that follow a desktop theme):

  • TextAlignmentRole
  • DisplayRole
  • FontRole
  • DecorationRole
  • ForegroundRole
  • BackgroundRole

NOTE: Each header renders data for each part itself and does not rely on delegates. Therefore, calling the header's setItemDelegate() function will have no effect.

Two, type members

1. enum QHeaderView::ResizeMode: The resize mode specifies the behavior of the header part.

  • Interactive: The user can adjust the size of the section. The section can also be resized programmatically using resizeSection().
  • Fixed: The section cannot be resized by the user. The section can only be resized programmatically using resizeSection().
  • Stretch: The section will be automatically resized to fill the available space. The size cannot be changed by the user or programmatically.
  • ResizeToContents: will automatically resize the section to the optimal size based on the content of the entire column or row. The size cannot be changed by the user or programmatically.

Three, attribute members

1、cascadingSectionResizes : bool

This property holds whether interactive resizing affects other sections once the section resized by the user reaches its minimum size.

This property only affects sections that have Interactive as their resizing mode.

The default value is false.

QTableView view;
QStandardItemModel *model = new QStandardItemModel(&view);
model->setColumnCount(3);
model->setRowCount(3);

QHeaderView * header = new QHeaderView(Qt::Horizontal);
header->setSectionResizeMode(QHeaderView::Interactive);
header->setCascadingSectionResizes(false);

view.setHorizontalHeader(header);

for (int i = 0;i < 3;++i)
{
for (int j = 0;j < 3;++j)
{
model->setData(model->index(i,j),"data");
}
}

view.setModel(model);
view.show();

header->setCascadingSectionResizes(true);

 

 

2、defaultAlignment : Qt::Alignment

This property holds the default alignment of text in each header section.

3、defaultSectionSize : int

  • This property holds the default size of the header section before resizing.
  • This property only affects sections that have Interactive or Fixed as their resizing mode.

By default, the value of this property depends on the style. Therefore, when the style changes, this property will update accordingly. Call setDefaultSectionSize() to stop updating, call resetDefaultSectionSize() to restore default behavior.

4、firstSectionMovable : bool

  • This property holds whether the first column can be moved by the user.
  • This property controls whether the user can move the first column.

In a QTreeView, the first column contains the tree structure and thus is not movable by default, even after setSectionsMovable(true). By calling this method, it can move again. In this case, it is recommended to also call QTreeView::setRootIsDecorated(false).

Setting this to true has no effect unless setSectionsMovable(true) is also called.

5、highlightSections : bool

This property holds whether the section containing the selected item is highlighted. The default is false.

6、maximumSectionSize : int

This property holds the maximum size of the header section.

The default value of this property is 1048575, which is also the maximum size. Setting the maximum value to -1 will reset the value to the maximum size.

This property is supported by all resizing modes except stretch.

7、minimumSectionSize : int

This property holds the minimum size of the header section.

All resizing modes support this property.

8、showSortIndicator : bool

This property holds whether the sort indicator is displayed. The default is false.

9、sortIndicatorClearable : bool

This property holds whether the sort indicator can be cleared by clicking a section multiple times.

Normally, clicking on a section only changes the sort order for that section. By setting this property to true, the sort indicator will clear after alternating ascending and descending order. This usually restores the original ordering of the model.

Setting this property to true has no effect unless sectionClickable() is also true.

10、stretchLastSection : bool

This property holds whether the last visible part of the title occupies all available space. The default value is false.

If this value is set to true, this property will override the resizing mode set by the last section in the header.

Note: The horizontal header provided by QTreeView is configured to set this property to true to ensure that the view does not waste any space allocated for its header.

4. Member functions

4.1. Signal

1、void geometriesChanged()

This signal is emitted when the header's geometry changes.

2、void sectionClicked(int logicalIndex)

This signal is emitted when a section is clicked.

Note that the sectionPressed() signal will also be emitted.

3、void sectionCountChanged(int oldCount, int newCount)

This signal is emitted when the number of columns changes, i.e. when a section is added or removed.

4、void sectionDoubleClicked(int logicalIndex)

This signal is emitted when a section is double-clicked.

5、void sectionEntered(int logicalIndex)

This signal is emitted when the cursor is moved over the part and the left mouse button is pressed.

6、void sectionHandleDoubleClicked(int logicalIndex)

This signal is emitted when a section is double-clicked.

7、void sectionMoved(int logicalIndex, int oldVisualIndex, int newVisualIndex)

This signal is emitted when a part is moved.

8、void sectionPressed(int logicalIndex)

This signal is emitted when a section is pressed.

9、void sectionResized(int logicalIndex, int oldSize, int newSize)

This signal is emitted when a section is resized.

10、void sortIndicatorChanged(int logicalIndex, Qt::SortOrder order)

This signal is emitted when a section containing a sort indicator or indicated order has changed.

4.2, function

1、void headerDataChanged(Qt::Orientation orientation, int logicalFirst, int logicalLast)

Updates changed header sections with the given direction, from logicalFirst to logicalLast inclusive.

2、void setOffset(int offset)

Set the offset of the header.

3、void setOffsetToLastSection()

Set the offset to make the last section visible.

4、int count()

Number of heading sections.

5、int hiddenSectionCount()

Returns the number of hidden sections in the header.

6、void hideSection(int logicalIndex) / void showSection(int logicalIndex)

Hide/show the section specified by logicalIndex.

7、bool isSectionHidden(int logicalIndex)

Whether a section is hidden.

8、int length()

Returns the length along the heading.

9、QByteArray saveState() / bool restoreState(const QByteArray &state)

Save/restore header state.

10、int sectionSize(int logicalIndex)

Returns the width (or height of a vertical header) for a given logical index.

11、void setResizeContentsPrecision(int precision)

Sets the precision with which to calculate sizes when using ResizeToContents. Lower values ​​will provide less accurate but fast auto-sizing, while higher values ​​will provide more accurate but possibly slow auto-sizing.

The default value is 1000, which means that a horizontal column with autoresize will look at a maximum of 1000 rows when doing the autoresize.

12、void swapSections(int first, int second)

Swap the two parts.

 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↓↓

QItemEditorFactory

1. Description

When editing data in the project view, the editor is created and displayed by the delegate. QStyledItemDelegate is the delegate installed by default on Qt item views, and it uses QItemEditorFactory to create editors for it. All item delegates use the default unique instance provided by QItemEditorFactory. If a new default factory is set using setDefaultFactory(), both existing and new delegates will use the new factory.

The factory holds a set of QItemEditorCreatorBase instances, which are specialized editors that generate editors for a particular QVariant data type (all Qt models store their data in QVariants).

Standard Edit Widget

Standard factory implementations provide editors for various data types. Editors are created whenever a delegate needs to provide an editor for the data provided by the model. The following is the relationship between types and the provided standard editors:

  • bool:QComboBox
  • double:QDoubleSpinBox
  • int、unsigned int:QSpinBox
  • QDate: QDateEdit
  • QDateTime:QDateTimeEdit
  • QPixmap:QLabel
  • QString:QLineEdit
  • QTime:QTimeEdit

Additional editors can be registered using the registerEditor() function.

Two, example

Color Editor Factory Example This demo demonstrates the usage of QItemEditorFactory.

class ColorListEditor : public QComboBox
{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor USER true)
public:
ColorListEditor(QWidget *widget = nullptr);
QColor color() const;
void setColor(QColor c);
};

ColorListEditor::ColorListEditor(QWidget *widget) : QComboBox(widget)
{
QStringList colorNames = QColor::colorNames();
for (int i = 0; i < colorNames.size(); ++i)
{
QColor color(colorNames[i]);
insertItem(i, colorNames[i]);
setItemData(i, color, Qt::DecorationRole);
}
}

QColor ColorListEditor::color() const
{
return qvariant_cast<QColor>(itemData(currentIndex(), Qt::DecorationRole));
}

void ColorListEditor::setColor(QColor color)
{
setCurrentIndex(findData(color, int(Qt::DecorationRole)));
}
Class Window : public QWidget
{
Q_OBJECT

public:
Window();
};

Window::Window()
{
QItemEditorFactory *factory = new QItemEditorFactory;
factory->registerEditor(QVariant::Color, new QStandardItemEditorCreator<ColorListEditor>());
QItemEditorFactory::setDefaultFactory(factory);

QList<QPair<QString, QColor> > list;
list << QPair<QString, QColor>(tr("Alice"), QColor("aliceblue")) <<
QPair<QString, QColor>(tr("Neptun"), QColor("aquamarine")) <<
QPair<QString, QColor>(tr("Ferdinand"), QColor("springgreen"));

QTableWidget *table = new QTableWidget(3, 2);
table->setHorizontalHeaderLabels(QStringList() << tr("Name")<< tr("Hair Color"));
table->verticalHeader()->setVisible(false);
table->resize(150, 50);

for (int i = 0; i < 3; ++i)
{
QPair<QString, QColor> pair = list.at(i);

QTableWidgetItem *nameItem = new QTableWidgetItem(pair.first);
QTableWidgetItem *colorItem = new QTableWidgetItem;
colorItem->setData(Qt::DisplayRole, pair.second);

table->setItem(i, 0, nameItem);
table->setItem(i, 1, colorItem);
}
table->resizeColumnToContents(0);
table->horizontalHeader()->setStretchLastSection(true);

QGridLayout *layout = new QGridLayout;
layout->addWidget(table, 0, 0);

setLayout(layout);
setWindowTitle(tr("颜色编辑工厂"));
}

QItemDelegate

1. Description

QItemDelegate can be used to provide custom display functionality and editor widgets for item views based on QAbstractItemView subclasses. Note that QStyledItemDelegate does the work of drawing the Qt item view. It is therefore recommended to use QStyledItemDelegate instead of QItemDelegate when creating new delegates.

When displaying items from a custom model in a view, it is often sufficient to ensure that the model returns appropriate data for each role that determines the appearance of the item in the view. The default delegates used by Qt views use this role information to display items in the most common forms the user expects. However, sometimes you need more control over the appearance of your project than the default delegate can provide.

When editing data in a view, the QItemDelegate provides an editor widget, which is a widget that is placed on top of the view while editing. Editors are created with a QItemEditorFactory; the default static instance provided by QItemEditorFactory is installed on all item delegates.

This class simply reimplements the standard editing functionality of widget-based delegates:

  • 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.
  • closeEditor(): Signals that the user is done editing data and the editor widget can be destroyed.

Standard roles and data types

The default delegates used by the standard views provided by Qt associate each standard role (defined by Qt::ItemDataRole) with certain data types. The models that return data in these types affect the appearance of the delegate as follows:

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

subclassing

When subclassing QItemDelegate to create a delegate that displays items using a custom renderer, it is important to ensure that the delegate can render items appropriately for all required states, such as checked, disabled, checked.

When a custom editor is required, there are two ways to achieve it:

The way without subclassing: use QItemEditorFactory to provide a custom editor.

How to subclass: Subclass QStyledItemDelegate and reimplement createEditor(), setEditorData(), setModelData(), and updateEditorGeometry().

2. Member functions

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

Creates and returns a widget for editing the item specified by index. parent and option are used to control how the editor widget is displayed.

2、void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)

Use the painter and option to render the index's item background.

3、void drawCheck(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, Qt::CheckState state)

Using painter and option, using state, renders the press indicator within the rectangle specified by rect.

4、void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QPixmap &pixmap)

Renders a decorative pixmap within the rectangle specified by rect using painter and option.

5、void drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text)

Renders the item view text within the rectangle specified by rect using painter and option.

6、void drawFocus(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect)

Renders the area within the rectangle specified by rect using painter and option, indicating it has focus.

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

Event filter. Returns true if the editor is a valid QWidget and the given event is handled, false otherwise.

The following key events are handled by default:

  • Tab
  • Backtab
  • Enter
  • Return
  • Esc

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 it is a Tab key event, the editor will be opened on the next item in the view.

In the case of a Backtab keypress event, the editor for the previous item in the view will be opened.

In the case of an Esc key press event, the editor closes without committing its data.

8、QItemEditorFactory * itemEditorFactory()

void setItemEditorFactory(QItemEditorFactory *factory)

The editor factory used by the project delegate.

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

Renders the delegate for the item specified by index using painter and option.

When reimplementing this function in a subclass, you should update the area held by the option's rect variable, use the option's state variable to determine the state of the item being displayed, and adjust how it is drawn accordingly.

For example, a checked item might need to be displayed differently than an unchecked item, as shown in the following code:

if (option.state & QStyle::State_Selected)
painter->fillRect(option.rect, option.palette.highlight());
else
...

After drawing you should be sure to return to the state provided when calling this function. (QPainter::save() / QPainter::restore() )

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/119641471

Guess you like

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