4

In order to expand the nodes of a TreeView to show the currently selected item (set by a shared selection model) I need to call TreeView.expand(QModelIndex) recursively.

    expand(index)
    expand(index.parent)
    expand(index.parent.parent)
    ...

this could be done by a function like this:

 function autoExpand(index ) {
    print(index)
    var oneUp = index

    do {

        print(oneUp)
        oneUp = index.parent
        expand(oneUp)
        print("do")
        print(oneUp)
    } while (oneUp)

}

however I don't know how to check for the root node. I tried

 while (oneUp)  -> always true
 while (oneUp.isValid) -> undefined ie always false
 while (oneUp.isValid()) -> property isValid cannot be called as a function

, in c++ it would be:

do {
   //....
} while (oneUp.isValid());

but I cannot find an equivalent function in QML (and don't know where to look for the code ...)

As a workaround I check it in c++ in an object that is already exported but well, it doesn't look proper:

public slots:
   bool indexIsValid(const QModelIndex &index) const {return index.isValid();}
Simon Schmeißer
  • 324
  • 4
  • 12

2 Answers2

3

As a side-effect of zizix's copy-paste answer I learned that the QModelIndex::isValid function translates to the index.valid property (?) in QML. Using that I can now successfully detect the root of a tree in QML:

function autoExpand(index ) {
        var oneUp = index

        do {
            oneUp = oneUp.parent
            expand(oneUp)                
        } while (oneUp.valid);

    }
Simon Schmeißer
  • 324
  • 4
  • 12
2

"...\Qt\5.5\Src\qtquickcontrols\src\controls\TreeView.qml"

function expand(index) {
        if (index.valid && index.model !== model)
            console.warn("TreeView.expand: model and index mismatch")
        else
            modelAdaptor.expand(index)
    }
zizix
  • 369
  • 1
  • 2
  • 5
  • Source code is available here: https://code.qt.io/cgit/qt/qtquickcontrols.git/tree/src/controls/TreeView.qml – Megidd Mar 30 '20 at 13:28