使用QListView列出文件夹文件时遇QAbstractItemView::setRootIndex报错
解决QAbstractItemView::setRootIndex失败的问题
嘿,我来帮你搞定这个Qt的报错问题!你遇到的QAbstractItemView::setRootIndex failed : index must be from the currently set model错误,其实是个很常见的小疏忽——你搞反了模型绑定和设置根索引的顺序。
错误原因
你当前的代码里,直接用listModel.setRootPath(directory)返回的索引去调用setRootIndex,但此时你的QListView(也就是ui->clusterList)还没有和listModel绑定。Qt要求setRootIndex传入的索引必须属于当前视图已经设置好的模型,所以自然就报错了。
修正步骤
只需要调整一下顺序,先把模型绑定到视图,再设置根索引就行:
- 第一步:先用
setModel()把listModel关联到你的QListView - 第二步:再调用
setRootIndex()传入setRootPath返回的索引
修正后的代码
QFileSystemModel listModel; QString directory = "/home/uboho/monitor_test_module/logs/tmp/etc/nodes"; // 第一步:先将模型绑定到视图 ui->clusterList->setModel(&listModel); // 第二步:再设置根索引 ui->clusterList->setRootIndex(listModel.setRootPath(directory));
额外注意事项
如果listModel是函数里的局部变量,要注意它的生命周期!如果函数执行完,listModel被销毁,你的QListView就会失去数据来源。这种情况下,建议把listModel改成类的成员变量,或者用动态分配的方式创建(让Qt帮你管理内存):
// 动态分配模型,将父对象设为当前窗口,Qt会自动处理内存释放 QFileSystemModel* listModel = new QFileSystemModel(this); QString directory = "/home/uboho/monitor_test_module/logs/tmp/etc/nodes"; ui->clusterList->setModel(listModel); ui->clusterList->setRootIndex(listModel->setRootPath(directory));
内容的提问来源于stack exchange,提问作者Blavida Ubee
相关产品推荐
相关产品推荐

