From 34c5b311fc6a8cb4c3d736a9bb41e78f5200bd2f Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 17 Mar 2025 16:00:43 +0100 Subject: [PATCH] QFileSystemModel: memoize roleNames() The return value of this function is constant and some users call this function often (an earlier version of QGenericItemModel did, possibly QML does?), so memoize the result of the function instead of re-creating the QHash on every call. Use QAbstractItemModelPrivate::defaultRoleNames() so we don't need an instance to get the base class' contents. Add a comment to keep the two in sync. As a drive-by, port from the QByteArrayLiteral macro to _ba UDLs. Amends 32b586864e3a4398da38c045f4ac0823c3dc3c57. Pick-to: 6.8 Change-Id: If00b51e60930c974e6f8f928711dc78ba1f42b93 Reviewed-by: Volker Hilsheimer (cherry picked from commit fde232c855d59009503fe6dbaadd10346ab0830a) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/itemmodels/qabstractitemmodel.cpp | 2 ++ src/gui/itemmodels/qfilesystemmodel.cpp | 16 +++++++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/corelib/itemmodels/qabstractitemmodel.cpp b/src/corelib/itemmodels/qabstractitemmodel.cpp index c298b0ca041..98b4fbf3f77 100644 --- a/src/corelib/itemmodels/qabstractitemmodel.cpp +++ b/src/corelib/itemmodels/qabstractitemmodel.cpp @@ -2655,6 +2655,8 @@ QSize QAbstractItemModel::span(const QModelIndex &) const */ QHash QAbstractItemModel::roleNames() const { + // if the return value ever becomes dependent on *this, also change the following overrides: + // - QFileSystemModel return QAbstractItemModelPrivate::defaultRoleNames(); } diff --git a/src/gui/itemmodels/qfilesystemmodel.cpp b/src/gui/itemmodels/qfilesystemmodel.cpp index 8cb68069cac..42d83775b8a 100644 --- a/src/gui/itemmodels/qfilesystemmodel.cpp +++ b/src/gui/itemmodels/qfilesystemmodel.cpp @@ -1269,13 +1269,15 @@ Qt::DropActions QFileSystemModel::supportedDropActions() const */ QHash QFileSystemModel::roleNames() const { - auto ret = QAbstractItemModel::roleNames(); - ret.insert(QFileSystemModel::FileIconRole, - QByteArrayLiteral("fileIcon")); // == Qt::decoration - ret.insert(QFileSystemModel::FilePathRole, QByteArrayLiteral("filePath")); - ret.insert(QFileSystemModel::FileNameRole, QByteArrayLiteral("fileName")); - ret.insert(QFileSystemModel::FilePermissions, QByteArrayLiteral("filePermissions")); - ret.insert(QFileSystemModel::FileInfoRole, QByteArrayLiteral("fileInfo")); + static auto ret = [] { + auto ret = QAbstractItemModelPrivate::defaultRoleNames(); + ret.insert(QFileSystemModel::FileIconRole, "fileIcon"_ba); // == Qt::decoration + ret.insert(QFileSystemModel::FilePathRole, "filePath"_ba); + ret.insert(QFileSystemModel::FileNameRole, "fileName"_ba); + ret.insert(QFileSystemModel::FilePermissions, "filePermissions"_ba); + ret.insert(QFileSystemModel::FileInfoRole, "fileInfo"_ba); + return ret; + }(); return ret; }