2017-12-18 295 views
-1

首先,假設存在一個存儲多個圖像的文件夾。然後,我嘗試單擊UI中的按鈕打開文件夾,然後將該文件夾中所有圖像的文件路徑保存到QList(僅限過濾的圖像文件)。但QList不存儲任何東西。請幫忙。如何從QT中的QFileSystemModel獲取文件路徑(C++)

void MainWindow::on_pushButton_clicked() 
{ 
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), 
               "/home", 
               QFileDialog::ShowDirsOnly 
               | QFileDialog::DontResolveSymlinks); 
    model = new QFileSystemModel(); 
    filesPath = dir; 
    model->setRootPath(dir); 
    QStringList filter; 
    filter <<"*.png" <<"*.jpg" <<"*.bmp" <<"*.gif"; 
    model->setNameFilters(filter); 
    model->setNameFilterDisables(false); 

    ui->treeView->setModel(model); 
    ui->treeView->setRootIndex(model->index(dir)); 
    ui->treeView->setAnimated(false); 
    ui->treeView->setSortingEnabled(true); 

    QList<QString> path_list; 
    QModelIndex parentIndex = model->index(dir); 
    int numRows = model->rowCount(parentIndex); 

    for (int row = 0; row < numRows; ++row) { 
     QModelIndex childIndex = model->index(row, 0, parentIndex); 
     QString path = model->data(childIndex).toString(); 
     if(!QFileInfo(path).isDir()) 
      path_list.append(path); 
    } 
} 
+0

你需要閱讀Qt文檔:http://doc.qt.io/qt-5/qfilesystemmodel.html#details –

+0

@ md612爲什麼你使用'QFileSystemModel'? –

+0

@Dmitry Sazonov將其與QtreeView – md612

回答

1

如果您使用QDir::entryList()而不是相應的過濾器,則可以實現您的目標,並且代碼和開銷更少。

+0

這確實是一個有用的答案,只是OP表示他需要一個項目模型來填充樹視圖。問題是爲什麼'QFileSystemModel'不能用於填充列表。哦,好吧......:P –

1

正如評論中提到的那樣,QFileSystemModel的設計並非如此。這裏的關鍵是在你指着(重點煤礦)的文檔:

不像QDirModel,QFileSystemModel使用一個單獨的線程來填充自身,所以不會造成主線程掛起,文件系統被查詢。 調用rowCount()將返回0,直到模型填充目錄。

如果你絕對想用QFileSystemModel建立一個列表,你必須一個功能連接到directoryLoaded(const QString &path)信號和每個文件夾中,一旦它被加載的文件添加...但也有大概是多少更好的方法來完成你所需要的。