我正在尝试模型/视图编程中的示例。
http://doc.qt.io/qt-5/model-view-programming.html
为了演示如何使用模型索引从模型中检索数据,我们设置了一个没有视图的 QFileSystemModel,并在小部件中显示文件和目录的名称。虽然这并没有展示使用模型的正常方式,但它展示了模型在处理模型索引时使用的约定。
我们通过以下方式构建文件系统模型:
QFileSystemModel *model = new QFileSystemModel;
QModelIndex parentIndex = model->index(QDir::currentPath());
int numRows = model->rowCount(parentIndex);
在这种情况下,我们设置了一个默认的 QFileSystemModel,使用该模型提供的 index() 的特定实现获取父索引,并使用 rowCount() 函数计算模型中的行数。
这是我的代码:
QFileSystemModel* model = new QFileSystemModel;
QModelIndex parentIndex = model->index(QDir::currentPath());
qDebug() << QDir::currentPath();
// "/media/Local Data/Files/Programming/C++/build-DemostrateQModelIndex-Desktop_Qt_5_5_1_GCC_64bit-Debug"
qDebug() << "RowCount is " << model->rowCount(parentIndex);
但 RowCount 始终为 0。
在“build-DemostrateQModelIndex-Desktop_Qt_5_5_1_GCC_64bit-Debug”文件夹中,里面有文件和文件夹。我希望行数应该是里面的项目数。
我也尝试过初始化 QFileSystemModel;
QFileSystemModel* model = new QFileSystemModel;
model->setRootPath(QDir::rootPath());
QModelIndex parentIndex = model->index(QDir::currentPath());
qDebug() << "RowCount is " << model->rowCount(parentIndex);
RowCount 仍为 0。
更新 1:应用 Johannes Schaub 的建议。QEventLoop
我在我的代码中添加了一个。
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFileSystemModel* model = new QFileSystemModel;
model->setRootPath(QDir::rootPath());
QModelIndex parentIndex = model->index(QDir::currentPath());
qDebug() << QDir::currentPath();
// "/media/Local Data/Files/Programming/C++/build-DemostrateQModelIndex-Desktop_Qt_5_5_1_GCC_64bit-Debug"
qDebug() << "First RowCount Call is " << model->rowCount(parentIndex);
QEventLoop loop;
QObject::connect(model, &QFileSystemModel::directoryLoaded, &loop, &QEventLoop::quit);
loop.exec();
qDebug() << "RowCount Call after eventloop is " << model->rowCount(parentIndex);
return a.exec();
}
我的行数仍然为 0。