Pergunta

I have a tree like this:

|-Parent
| |-Child-Child
|-Parent
| |-Child-Child
...

Only the Parents are selectable. How can I get the data from the selected Parent?

I tried

ui->treeView->selectedIndexes()[0];  

but it says that selectedIndexes() is protected.

Foi útil?

Solução

You need to call QItemSelectionModel::selectedIndexes() instead, i.e.:

QModelIndexList indexes = ui->treeView->selectionModel()->selectedIndexes();
if (indexes.size() > 0) {
    QModelIndex selectedIndex = indexes.at(0);
    [..]
}

Outras dicas

How to get the selected item in a QTreeView? The question is simple and the answers are terrible, and the tutorial worse.

Below is a fully functional example which shows how to get the selected item. Specifically selected_item()

#include <QApplication>
#include <QTreeView>
#include <QStandardItemModel>
#include <QItemSelectionModel>
#include <QGridLayout>
#include <iostream>

struct Node:public QStandardItem {
    Node(std::string name):QStandardItem(name.c_str()){}
    virtual void operator()(){
        std::cout<<"selected node named: "<<text().toStdString()<<std::endl;
    }
};

class TreeView :public QWidget{

    Q_OBJECT
public:
    QTreeView tree;

    using Model=QStandardItemModel;
    Model* item_model(){        return (Model*)tree.model();    }
    Node* selected_item() {
        QModelIndex index = tree.currentIndex();
        if(!index.isValid()) return nullptr; // if the user has selected nothing
        return (Node*)(item_model()->itemFromIndex(index));
    }
    TreeView() {
        // automatically sets to parent
        auto layout=new QGridLayout(this);
        layout->addWidget(&tree,0,0);

        // set the item model, there is no sane choice but StandardItemModel
        tree.setModel(new Model());
        connect(tree.selectionModel(),
                &QItemSelectionModel::selectionChanged,
                this,
                &TreeView::selected);
        // create a small tree
        auto top=new Node("top");
        auto a=new Node("a");
        a->appendRow(new Node("a0"));
        a->appendRow(new Node("a1"));
        auto b=new Node("b");
        top->appendRow(a);
        top->appendRow(b);
        // add it to the treeview root
        item_model()->invisibleRootItem()->appendRow(top);
    }

private slots:
    void selected(
            const QItemSelection &news, // not used
            const QItemSelection &olds)
    {
        auto* node=selected_item();
        if(node) (*node)();
    }
};


int main(int argc, char** argv){

    QApplication a(argc, argv);
    TreeView w;
    w.show();
    return a.exec();


}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top