[kio] src/widgets: Reimplement sibling(), faster than the default impl which goes via parent()

David Faure faure at kde.org
Sun May 4 11:41:58 UTC 2014


Git commit 23d81eb86ae45828f8a56d2b0447de0a0f20aa86 by David Faure.
Committed on 04/05/2014 at 11:40.
Pushed by dfaure into branch 'master'.

Reimplement sibling(), faster than the default impl which goes via parent()

It wasn't virtual until Qt 5.0.

We should do this for all tree models...
CCMAIL: kde-frameworks-devel at kde.org

M  +19   -1    src/widgets/kdirmodel.cpp

http://commits.kde.org/kio/23d81eb86ae45828f8a56d2b0447de0a0f20aa86

diff --git a/src/widgets/kdirmodel.cpp b/src/widgets/kdirmodel.cpp
index d88a169..70d5ee4 100644
--- a/src/widgets/kdirmodel.cpp
+++ b/src/widgets/kdirmodel.cpp
@@ -900,7 +900,6 @@ int KDirModel::rowCount(const QModelIndex &parent) const
     return count;
 }
 
-// sibling() calls parent() and isn't virtual! So parent() should be fast...
 QModelIndex KDirModel::parent(const QModelIndex &index) const
 {
     if (!index.isValid()) {
@@ -913,6 +912,25 @@ QModelIndex KDirModel::parent(const QModelIndex &index) const
     return d->indexForNode(parentNode); // O(n)
 }
 
+// Reimplemented to avoid the default implementation which calls parent
+// (O(n) for finding the parent's row number for nothing). This implementation is O(1).
+QModelIndex KDirModel::sibling(int row, int column, const QModelIndex &index) const
+{
+    if (!index.isValid()) {
+        return QModelIndex();
+    }
+    KDirModelNode *oldChildNode = static_cast<KDirModelNode *>(index.internalPointer());
+    Q_ASSERT(oldChildNode);
+    KDirModelNode *parentNode = oldChildNode->parent();
+    Q_ASSERT(parentNode);
+    Q_ASSERT(d->isDir(parentNode));
+    KDirModelNode *childNode = static_cast<KDirModelDirNode *>(parentNode)->m_childNodes.value(row); // O(1)
+    if (childNode) {
+        return createIndex(row, column, childNode);
+    }
+    return QModelIndex();
+}
+
 static bool lessThan(const QUrl &left, const QUrl &right)
 {
     return left.toString().compare(right.toString()) < 0;


More information about the Kde-frameworks-devel mailing list