モデル/ビュープログラミングの例を試しています。
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の行数を取得します。