如何在QTreeView中获取所选项目
How to get the selected item in a QTreeView
我有这样一棵树:
|-家长
| |-儿童-儿童
|-家长
| |-儿童-儿童
...
只有父项是可选的。如何从所选父级获取数据?
我试过了
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();
}
相关文章:
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- C++项目编译强制使用 /clr 选项,尽管在没有公共语言运行时支持的情况下执行它
- 暂时将C++项目(VS2015)移至Android操作系统.编译器选项?
- 是否有任何 MSBuild 命令行选项可以动态禁用 c++ 项目的代码分析?
- 用于在 Visual Studio 中为整个项目或解决方案定义带有参数的预处理器宏的选项
- 如何将cacert.pem与vs2015 curl项目一起包含,因此无需指定Cainfo curl选项
- Visual Lint?中的每个项目选项
- C++:使用 g++ 和 -m32 选项构建的 c++ 库在 Msys 下构建 wxWidgets 项目时出现 ld 不
- 如何在 eclipse makefile 项目中的编译器选项中设置 -std=c++0x
- 无法使项目,无法识别的命令行选项libc ++错误
- 将cmake构建选项导出到外部项目
- 为什么c++透视图和新项目选项在Eclipse中不可用
- 4.9.9.2项目选项不工作
- 无法使用/ CLR选项从Visual c++项目加载CLR
- 如何将code::块设置为在目标链接器选项之前链接项目链接器选项
- 可以qmake-configure Visual Studio项目中的命令行选项
- 在我的项目中使用预编译的头(clang/llvm,但也使用gcc).如何在make中部署-include选项
- 从下拉框中选择其他项目时更改选项卡小部件的 currentIndex()
- 使用 /Command 选项从命令行为 Visual Studio C++ 项目创建一个新文件
- 向Eclipse CDT Autotools项目添加链接器选项