在QFileSystemModel中查找第n个文件/文件夹
我正在使用QFileSystemModel和QTreeView,我试图让TreeView默认选择第一个文件夹/文件。为此,我需要获取第一个文件夹/文件的索引,但我找不到在QFileSystemModel中执行此操作的方法。在QFileSystemModel中查找第n个文件/文件夹
你能帮我吗?
预先感谢您。
我试过setCurrentIndex(_model->index(x, y))
但它没有工作。下面是我的代码,并显示该树:
void CodeView::finished_loading(QString file) {
qDebug()<<"Currently selected : " << _model->fileName(ui->treeView->currentIndex());
qDebug()<<"(0,0) "<< _model->fileName(_model->index(0,0));
qDebug()<<"(1,0) "<< _model->fileName(_model->index(1,0));
qDebug()<<"(2,0) "<< _model->fileName(_model->index(2,0));
qDebug()<<"(3,0) "<< _model->fileName(_model->index(3,0));
qDebug()<<"(0,0) "<< _model->fileName(_model->index(0,0));
qDebug()<<"(1,1) "<< _model->fileName(_model->index(1,1));
qDebug()<<"(2,1) "<< _model->fileName(_model->index(2,1));
qDebug()<<"(3,1) "<< _model->fileName(_model->index(3,1));
ui->treeView->setCurrentIndex(_model.index(1,0));
qDebug()<<"New selected : " << _model->fileName(ui->treeView->currentIndex());
}
输出:
Currently selected : "Wassim Gharbi"
(0,0) "/"
(1,0) ""
(2,0) ""
(3,0) ""
(0,0) "/"
(1,1) ""
(2,1) ""
(3,1) ""
New selected : "Wassim Gharbi"
的方法不在模式,而是在视图中。
QTreeView::setCurrentIndex
从文档:
QAbstractItemView中:: setCurrentIndex(常量QModelIndex &索引)设置 当前项是在索引的项。
除非当前选择模式为NoSelection,否则该项目也会被选中 。请注意,此功能还会为用户执行的任何新选择更新起始位置 。
要设置的项作为当前项但不选择它,呼叫
selectionModel的() - > setCurrentIndex(索引, QItemSelectionModel :: NOUPDATE);
另请参阅currentIndex(),currentChanged()和selectionMode。
的第一个文件夹中的代码是不是真的容易,乍看之下,但你要记住,对模型的数据抽象使得它强大的,并且cumberstone在同一时间,所以任何项目可能是一个文件夹或文件,我们需要检查的是:
if (model->rowCount()) // has at least one file or folder
{
QModelIndex current = model->index(0,0);
if (model->rowCount(current) == 0); // it's a file.
return current;
else {
// walk the tree trying to find the first file on the folders.
while(model->rowCount(current) > 0) {
current = model->index(0,0,current);
}
if (index.isValid())
return index; // our file inside folders
else
return QModelIndex(); // no file inside folders.
}
}
你好,感谢你的快速回复。其实,我不在乎它是一个文件还是一个文件夹,我只想选择树中的第一个项目。请看看最新的问题。 –
他的回答是过分复杂的事情。他通过调用'QStandardItemModel :: index(row,column,parentIndex)'来调用'QModelIndex :: child()'。他究竟在哪里回来?你还说你不关心这个物品的类型? – mrg95
暗示这是在函数调用中,至少我认为它是隐含的。 :)他说(在编辑之前(我想拥有第一个文件,因为第一个文件可能在一连串文件夹中,这是我能想到的最快解决方案。) –
为了获得在模型上的特定位置的索引,使用QModelIndex::child(row, column)
QFileSystemModel *model = new QFileSystemModel();
model->setRootPath("C:/Qt");//your path
ui->treeView->setModel(model);
ui->treeView->setCurrentIndex(model->index(0, 0).child(0, 0));
我可以从你的追求告诉你不明白树视图的行和列系统是如何工作的。请阅读documentation
请参阅更新的问题,idx。 child(0,0)'does not really work ... –
我编辑了我的答案。因为你没有设置根索引,所以你仍然可以在'model-index'的索引处调用'QModelIndex :: child() > index(0,0)' 我可以从你的问题中知道你不明白树视图的行和列系统是如何工作的,请阅读文档:http://doc.qt.io/qt-4.8/模型 - 视图 - programming.html#模型类 – mrg95
'model-> index(x,y)'中的第二个参数不代表子项目。它实际上代表了修改日期,文件大小,名称等项目的列。 请查看我的答案,以了解如何获取父索引的子索引。 – mrg95