如何在QTreeView中获取所选项目

How to get the selected item in a QTreeView

本文关键字:选项 项目 获取 QTreeView      更新时间:2023-10-16

我有这样一棵树:

|-家长
| |-儿童-儿童
|-家长
| |-儿童-儿童
...

只有父项是可选的。如何从所选父级获取数据?

我试过了

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

但它说 selectedIndexes() 是受保护的。

你需要调用QItemSelectionModel::selectedIndexes(),即:

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

如何在QTreeView中获取所选项目?问题很简单,答案很糟糕,教程更糟糕。

下面是一个功能齐全的示例,显示了如何获取所选项目。具体来说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();

}