Please nominate your Qt Champions for 2021!

Cycling through the items of TreeModel

  • I need to cycle through the items of a TreeModel.


    And I need to browse through them a bit like this:
    anItem ; anotherItem ; aChild ; anotherChild ; andSoOn
    Is there an iterator going through all the items or do I have to write a kind of "++" operator doing the tests (child is valid and so on)?

    I'm writing something like that:

    void itemIndexPlusPlus(QModelIndex &index){
        int indexRowBuf;
        if (index.child(0,0).isValid())//if has child
            index = index.child(0,0);
        else if (index.parent().child(index.row()+1, 0).isValid())//if has buddy following
            index = index.parent().child(index.row()+1, 0);
        else {
            while ((index != rootIndex())) {//ascend to the master excepted if children of row+1
                indexRowBuf = index.row();
                index = index.parent();
                if (index.child(indexRowBuf + 1, 0).isValid()) {
                    index = index.child(indexRowBuf + 1, 0);

    But first it's not very stylish : long code and plenty of tests for something simple and then, I don't like to reinvent the wheel. Qt has plenty of wheels, but I sometimes have difficulties to find the good one...


  • How about recursion? for example:

    void printModel(const QAbstractItemModel* const model, const QModelIndex& parent = QModelIndex()) {
      const int rowCount = model->rowCount(parent);
      if(model->columnCount(parent) == 0) { return; }
      for(int i = 0; i < rowCount; ++i) {
        const QModelIndex currIdx = model->index(i, 0, parent);
        qDebug() <<;
        if(model->hasChildren(currIdx)) {
          printModel(model, currIdx);      
    } // printModel

    then call it with printModel(treeModel);

  • It seems to work.

    Recursion was an old souvenir in my studies...

    Thanks to you, you contributed to my programmer experience :)

  • One question : why are all the arguments const ?

  • It's the most permissive way. with all those consts you can call the function with arguments of any constness. for example:

    QAbstractItemModel* model; printModel(treeModel); //works
    const QAbstractItemModel* model; printModel(treeModel); //works
    QAbstractItemModel* const model; printModel(treeModel); //works
    const QAbstractItemModel* const model; printModel(treeModel); //works

    Of course I could do that because all I do in that function is print values from model to the console. if you want to change values in the model you have to lose the first const so: void printModel(QAbstractItemModel* const model, const QModelIndex& parent = QModelIndex()) but now if you try to call it with a const model (const QAbstractItemModel* model; printModel(treeModel);) it will fail to compile

Log in to reply