Search code examples
c++qtqtreeview

Get the strings from a List of QtreeView


I want to get the Strings from a List of QtreeView.

In my qtreeview i have:

   [*] Node1
        [*] Subnode1_1
            test_1
            test_2
    [*] Node2
        test_3
        [*] Subnode2_1
            test_4    
    test_5

and I want to get Strings: test_1, test2, test3, test4, test5 To start a request in a database.

The only thing i found is get the String from the node you selected.

by : Tree->model()->itemData(m_listOfModelIndex.at(0))[Qt::DisplayRole].toString()

Thanks


Solution

  • QStringList strings = extractStringsFromModel(Tree->model(), QModelIndex());
    

    Implementation of extractStringsFromModel

    QStringList extractStringsFromModel(QAbstractItemModel *model, const QModelIndex &parent)
    {
        QStringList retval;
    
    
        int rowCount = model->rowCount(parent);
    
        for(int i = 0; i < rowCount; ++i)
        {
            QModelIndex idx = model->index(i, 0, parent);
    
            if(idx.isValid())
            {
                retval << idx.data(Qt::DisplayRole).toString();
                retval << extractStringsFromModel(model, idx);
            }
        }
    
        return retval;
    }
    

    This recursive function will extract ALL texts from your model. If you want to get "specific" data, then you should add some filtering. But basicly it will go through whole tree.