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();
}