Qt model view framework: QAbstractItemDelegate, QFileSystemModel

QAbstractItemDelegate

1. Description

QAbstractItemDelegate provides an interface and common functionality for delegation in the model/view framework. The delegate displays individual items in the view and handles editing of model data.

To render items in a custom way, you must implement paint() and sizeHint(). The QStyledItemDelegate class provides default implementations for these functions, if you don’t need custom rendering, subclass the QStyledItemDelegate class instead.

Give an example of drawing a progress bar in items;

Create the WidgetDelegate class, which inherits from QStyledItemDelegate. Draw in the paint() function:

void WidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem & amp;option,
const QModelIndex & index) const
{
if (index. column() == 1) {
int progress = index. data(). toInt();

QStyleOptionProgressBar progressBarOption;
progressBarOption.rect = option.rect;
progressBarOption.minimum = 0;
progressBarOption. maximum = 100;
progressBarOption.progress = progress;
progressBarOption.text = QString::number(progress) + "%";
progressBarOption.textVisible = true;

QApplication::style()->drawControl(QStyle::CE_ProgressBar, & amp;progressBarOption, painter);
} else
QStyledItemDelegate::paint(painter, option, index);
}

To provide custom editing, two methods can be used:

The first way is to create an editor widget and display it directly on top of the item. You must reimplement createEditor() to provide an editor widget, reimplement setEditorData() to populate the editor with data from the model, and reimplement setModelData() so that the delegate can update the model with data from the editor.

The second way is to handle user events directly by reimplementing editorEvent() .

2. Type members

1. enum QAbstractItemDelegate::EndEditHint: This enumeration describes the different hints that the delegate can give to model and view components to optimize the experience of editing data in the model.

  • NoHint: No suggested action.
  • These hints let the delegate affect the behavior of the view:
  • EditNextItem: The view should use the delegate to open the editor on the next item in the view.
  • EditPreviousItem: The view should use the delegate to open the editor for the previous item in the view.
  • Note that custom views may interpret the previous item and next item concepts differently.
  • The following tips are most useful when caching data with models:
  • SubmitModelCache: If the model caches data, it should write out the cached data to the underlying data store.
  • RevertModelCache: If the model caches data, it should discard the cached data and replace it with data from the underlying data store.

3. Member functions

3.1. Signal

1. void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint = NoHint)

This signal is emitted when the user has finished editing the item using the specified editor.

NoHint provides a way for delegates to affect the behavior of models and views after editing is complete. It instructs these components what should be done next in order to provide a comfortable editing experience for the user. For example, if EditNextItem is specified, the view should use the delegate to open the editor on the next item in the model.

2. void commitData(QWidget *editor)

This signal must be emitted when the editor widget has finished editing data and wants to write it back to the model.

3. void sizeHintChanged(const QModelIndex & amp;index)

This signal must be emitted when the sizeHint() of index changes. Views automatically connect to this signal and rearrange items as necessary.

3.2, function

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

Returns an editor for editing the data item with the given index.

Indexes contain information about the model being used. The editor’s parent widget is specified by parent and item options are specified by option .

If you want custom editing, you need to reimplement this functionality. (to set the style sheet must be set on the parent)

The editor widget returned by focusPolicy() should have Qt::StrongFocus; otherwise MouseEvents received by the widget will be propagated to the view.

The view’s background glows unless the editor draws its own background (for example, using setAutoFillBackground() ).

2. void destroyEditor(QWidget *editor, const QModelIndex & amp;index)

Called when the editor no longer needs to edit the data item with the given index and should be destroyed. The default behavior is to call deleteLater() on the editor. Delete or other custom actions can be avoided by reimplementing this function.

3. bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem & amp;option, const QModelIndex & amp;index)

When editing an item begins, this function is called with the event that triggered the edit, the model, the item index, and options for rendering the item.

Mouse events are sent to editorEvent() even if the mouse event did not start editing an item. This is useful, for example, if you want the context menu to open when the right mouse button is pressed on an item.

The base implementation returns false (indicating that it has not handled the event).

4. bool helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index)

Whenever a help event occurs, this function is called with the event view options and the index corresponding to the item on which the event occurred.

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

If you want to provide custom rendering, you must reimplement this pure virtual function. Renders the item specified by the item index using the painter and style options.

If this function is reimplemented it must also implement sizeHint().

6. void setEditorData(QWidget *editor, const QModelIndex & amp;index)

Sets the content of the given editor as the data for the item at the given index. Indexes contain information about the model being used.

7. void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex & amp;index)

Sets the item data at the given index in the model as the content of the given editor.

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

size hint.

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

Updates the editor’s geometry for the item with the given index, according to the rectangle specified in the options.

The benefits of this article,Fees 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 actual combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article to receive the fee↓↓

QFileSystemModel

1. Description

This class provides access to the local file system, providing functionality to rename and delete files and directories, and to create new directories. In the simplest case, it can be used with a widget, as part of a browser or a filter.

QFileSystemModel can be accessed using the standard interface provided by QAbstractItemModel , but it also provides some convenience functions specific to directory models.

Note: QFileSystemModel requires an instance of QApplication.

default usage

QFileSystemModel *model = new QFileSystemModel;
model->setRootPath(QDir::currentPath());

QTreeView tree;
tree.setModel(model);
tree.setRootIndex(model->index(QDir::currentPath()));
tree. show();

Caching and Performance

QFileSystemModel does not fetch any files or directories until setRootPath() is called.

QFileSystemModel uses a separate thread to query files and directories in order to populate the model data, so it does not cause the main thread to hang while querying the file system.

QFileSystemModel holds a cache containing file information. The cache is automatically kept up to date using QFileSystemWatcher.

2. Type members

1. enum QFileSystemModel::Option:

  • DontWatchForChanges: Don’t add file watchers to paths. This reduces overhead when using the model for simple tasks like row edit completion.
  • DontResolveSymlinks: Do not resolve symbolic links in the filesystem model.
  • DontUseCustomDirectoryIcons: Always use the default directory icons. Some platforms allow users to set different icons. Custom icons can have a significant impact on network or removable drive performance.

2. enum QFileSystemModel::Roles

  • FileIconRole: Qt::DecorationRole
  • FilePathRole: Qt::UserRole + 1
  • FileNameRole: Qt::UserRole + 2
  • FilePermissions: Qt::UserRole + 3

Three, attribute members

1. nameFilterDisables: bool

Whether files that fail the name filter are hidden or disabled, defaults to true.

2. options: Options

This property contains various options that affect the model. By default, all options are disabled.

3. readOnly: bool

This property holds whether the directory model allows writing to the file system. Defaults to true.

If this property is set to false, the directory model will allow renaming, copying, and deletion of files and directories.

4. resolveSymlinks: bool

This property holds whether the directory model should resolve symlinks. Defaults to true.

4. Member functions

4.1. Signal

1. [signal] void directoryLoaded(const QString & amp; path)

This signal is emitted when threads querying files and directories have finished loading paths.

2. [signal] void fileRenamed(const QString & amp;path, const QString & amp;oldName, const QString & amp;newName)

This signal is emitted whenever a file with oldName is successfully renamed to newName. The file is located in the directory path.

3. [signal] void rootPathChanged(const QString & amp;newPath)

This signal is emitted whenever the root path changes to newPath.

4.2, function

1. QIcon fileIcon(const QModelIndex & index)

  • QFileInfo fileInfo(const QModelIndex & index)
  • QString fileName(const QModelIndex & index)
  • QString filePath(const QModelIndex & index)

Returns the icon, QFileInfo, filename, path of the item stored at the given index in the model.

2. QAbstractFileIconProvider * iconProvider() / void setIconProvider(QAbstractFileIconProvider *provider)

Returns the file icon provider for this directory model.

3. QModelIndex index(const QString & amp; path, int column = 0)

Returns the model item index for the given path and column.

4. bool isDir(const QModelIndex & index)

Returns true if the model item index represents a directory, false otherwise.

5. QDateTime lastModified(const QModelIndex & amp;index)

Returns the date and time when the index was last modified.

6. QModelIndex mkdir(const QModelIndex & amp; parent, const QString & amp; name)

Create a directory with name from the parent model index.

7. QVariant myComputer(int role = Qt::DisplayRole)

Returns the data stored for the item “My Computer” under the given role.

8. bool remove(const QModelIndex & index)

Removes the model item index from the filesystem model and deletes the corresponding file from the filesystem, returning true if successful. Returns false if the item could not be removed.

Warning: This function deletes files from the file system; it does not move them to a location where they can be restored.

9. bool rmdir(const QModelIndex & index)

Delete the directory corresponding to the model item index in the file system model, and delete the corresponding directory from the file system, and return true if successful. Returns false if the directory could not be removed.

Warning: This function deletes directories from the filesystem; it does not move them to a location where they can be restored.

10. QDir rootDirectory()

The currently set directory.

11. QString rootPath()

The currently set root path.

12. void setFilter(QDir::Filters filters)

Set the filter for the model. Note that the filter set should always contain the QDir::AllDirs enumeration value, otherwise the QFileSystemModel will not be able to read the directory structure.

13. void setNameFilters(const QStringList & filters)

Set a name filter to apply to existing files.

14. void setOption(QFileSystemModel::Option option, bool on = true)

If on is true, sets the given option to enable; otherwise, clears the given option.

15. QModelIndex setRootPath(const QString & newPath)

Set the watched directory to newPath. Any changes to files and directories within this directory will be reflected in the model.

If the path changes, the rootPathChanged() signal will be emitted.

16. qint64 size(const QModelIndex & index)

Returns the byte size of the index. Returns 0 if the file does not exist.

17. bool testOption(QFileSystemModel::Option option)

Returns true if the given option is enabled, false otherwise.

18. QString type(const QModelIndex & index)

Returns the type of file index, such as “directory” or “JPEG file” (“Directory” or “JPEG file”).

The benefits of this article,Fees 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 actual combat, QT embedded development, Quick module, etc.) ↓↓↓↓↓↓See below↓↓Click at the bottom of the article to receive the fee↓↓

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