我正在阅读MVC教程并希望尝试代码,但由于某种原因(我无法弄清楚)它无法正常工作。
此代码用于显示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();
}
答案 0 :(得分:4)
有两个问题。
第一个described by Frank Osterfeld's answer。移动:
QListWidgetItem *newItem = new QListWidgetItem;
进入你的循环。
第二个与QFileSystemModel
的线程模型有关。来自QFileSystemModel
的文档:
与QDirModel不同,QFileSystemModel使用单独的线程来填充自身,因此在查询文件系统时不会导致主线程挂起。调用rowCount()将返回0,直到模型填充目录。
和
注意:QFileSystemModel需要GUI应用程序的实例。
我认为QFileSystemModel()
在运行Qt事件循环之后才能正常工作(在您的示例中由a.exec()
启动)。
在你的情况下,model->rowCount(parentIndex)
返回0,即使目录中有项目(至少这是我在测试中所做的)。
用QFileSystemModel
替换QDirModel
(以及删除QDirModel`不支持的model->setRootPath(dir)
调用)填充列表。
答案 1 :(得分:1)
您必须为每一行创建一个新项目。移动
QListWidgetItem *newItem = new QListWidgetItem;
进入for循环。