簡體   English   中英

在QFileSystemModel中找到第n個文件/文件夾

[英]Find nth file/folder in QFileSystemModel

我正在使用QFileSystemModel和QTreeView,並且嘗試使TreeView默認選擇第一個文件夾/文件。 為此,我需要獲取第一個文件夾/文件的索引,但是我找不到在QFileSystemModel中執行此操作的方法。

請你幫助我好嗎?

先感謝您。


我已經嘗試過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(const QModelIndex&index)設置當前項目為索引處的項目。

除非當前選擇模式為NoSelection,否則也將選擇該項目。 請注意,此功能還會更新用戶執行的任何新選擇的開始位置。

要將一個項目設置為當前項目而不選擇它,請調用

selectionModel()-> setCurrentIndex(index,QItemSelectionModel :: NoUpdate);

另請參見currentIndex(),currentChanged()和selectionMode。

乍一看,第一個文件夾的代碼並不是一件容易的事,但是您需要記住,模型上的數據抽象使它既強大又麻煩,因此任何項目都可能是文件夾或文件,而我們需要檢查一下:

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.
   }
}

為了獲得模型中特定位置的索引,請使用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));

從您的問題中可以看出,您不了解Treeview的行和列系統的工作方式。 請閱讀文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM