What is wrong with this Qt code?

I read the MVC tutorial and wanted to try the code, but for some reason (which I cannot understand) it does not work.

This code should show the contents of the current directory in a QListWidget.

#include <QApplication> #include <QFileSystemModel> #include <QModelIndex> #include <QListWidget> #include <QListView> int main(int argc, char *argv[]) { QApplication a(argc, argv); QFileSystemModel *model = new QFileSystemModel; QString dir = QDir::currentPath(); model->setRootPath(dir); QModelIndex parentIndex = model->index(dir); int numRows = model->rowCount(parentIndex); QListWidget *list = new QListWidget; QListWidgetItem *newItem = new QListWidgetItem; for(int row = 0; row < numRows; ++row) { QModelIndex index = model->index(row, 0, parentIndex); QString text = model->data(index, Qt::DisplayRole).toString(); newItem->setText(text); list->insertItem(row, newItem); } list->show(); return a.exec(); } 
-1
source share
2 answers

There are 2 problems.

The first described by Frank Osterfeld . Moving:

 QListWidgetItem *newItem = new QListWidgetItem; 

into your cycle.

The second is related to the QFileSystemModel model. from the docs for QFileSystemModel :

Unlike QDirModel, QFileSystemModel uses a separate thread to populate, so it will not cause the main thread to hang when the file system is requested. Calls to rowCount () return 0 until the model populates the directory.

and

Note. QFileSystemModel requires an instance of a GUI application.

I do not think that QFileSystemModel() will work properly until the Qt loop cycle is started (which is launched by a.exec() in your example).

In your case, model->rowCount(parentIndex) returns 0, even if it has elements in it (at least what it does in my test).

Replacing QFileSystemModel with QDirModel (and removing the call to model->setRootPath(dir) , which is not supported by QDirModel) fills the list.

+4
source

You must create a new item for each row. Move

 QListWidgetItem *newItem = new QListWidgetItem; 

into the for loop.

+1
source

All Articles