Multithreading 当我从构造函数中调用自己的填充函数时,QTreeView/qabstractemodel只显示数据
我已经实现了EditableTreeModel示例中的代码,当我使用自己的函数构建目录树时,它工作得很好。My functions是TreeModel类的公共成员,定义如下:Multithreading 当我从构造函数中调用自己的填充函数时,QTreeView/qabstractemodel只显示数据,multithreading,qt,constructor,qtreeview,qabstractitemmodel,Multithreading,Qt,Constructor,Qtreeview,Qabstractitemmodel,我已经实现了EditableTreeModel示例中的代码,当我使用自己的函数构建目录树时,它工作得很好。My functions是TreeModel类的公共成员,定义如下: void TreeModel::construct(TreeItem *parent, QString path,uint32_t parentID){//fileide of the parent QDirIterator dir(path,QDir::NoDotAndDotDot | QDir::NoSymLinks
void TreeModel::construct(TreeItem *parent, QString path,uint32_t parentID){//fileide of the parent
QDirIterator dir(path,QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Files | QDir::Dirs | QDir::Readable,QDirIterator::NoIteratorFlags);
QFileInfo file; QString curPath;TreeItem *child;
helix::ResourceEntry entry; uint32_t fileID = parentID;
while(dir.hasNext()){
curPath = dir.next();
file = dir.fileInfo();
entry.name = dir.fileName().toStdString();
entry.parent = parentID;
entry.fileID = ++fileID;
if(parent->childCount() > 0){
//if we have a previous child, set its next id to point on the current entry
child = parent->child(parent->childCount() - 1);
child->resourceEntry.next = fileID;
}
if(file.isDir()){
entry.entryType = helix::HRESOURCE_ENTRY_TYPE_E::directory;
}else{
entry.entryType = helix::HRESOURCE_ENTRY_TYPE_E::file;
entry.size = file.size();
}
//Insert a new child
if(parent->insertChildren(parent->childCount(), 1, rootItem->columnCount())){
child = parent->child(parent->childCount() - 1);
child->setData(0, QVariant(dir.fileName()));
child->resourceEntry = entry;
child->path = curPath;
//traverse into subdir if it is not empty
if(file.isDir() && QDir(curPath).count() > 0) construct(child,curPath,entry.fileID);
}
}
}
当我从TreeModel构造函数调用此函数时,如下所示:
TreeModel::TreeModel(/*const QStringList &headers, const QString &data, */QObject *parent)
: QAbstractItemModel(parent)
{
QVector<QVariant> rootData; rootData << "Entry";
rootItem = new TreeItem(rootData);
rootItem->resourceEntry.fileID = 0;
construct(rootItem,"D:\\tmp",0);
}
TreeModel::TreeModel(/*const-QStringList&headers,const-QString&data,*/QObject*parent)
:qabstractemmodel(父级)
{
QVector rootData;rootData resourceEntry.fileID=0;
构造(rootItem,“D:\\tmp”,0);
}
它工作正常,所有条目都正确显示。但是如果我从类外调用这个函数,什么也不会发生:model->construct(model->getRootItem(),“D:\\tmp”,0)代码>
我的目标是使用一个线程来实现构造函数并将根项传递给thead,但我注意到treeview没有显示数据,这就是为什么我将函数复制到TreeModel.cpp并从构造函数调用if。这是对模型的某种限制,它只能从构造函数初始化吗
任何提示或提示都将不胜感激
谢谢,Fabian好的,它完全可以理解它不起作用:我需要在调用ui.treeView->setModel(model)
之前构造模型,所以在我的例子中,当线程执行完上面的构造函数后,我调用ui.treeView->reset()
,然后调用ui.treeView->setModel(model)
。现在一切正常。你说的“什么都没发生”是什么意思?您能调试它并查看代码是否正确执行吗?除了作为练习留给您的基本调试之外,Qt模型不是这样构造的。假设您要实现诸如parent()、rowCount()等函数。。并根据视图的需要在那里“动态”构建模型。不要使用这种递归噩梦。所谓“什么都没有发生”,我的意思是树视图不会像我从构造函数调用构造函数时那样显示条目。模型必须这样构造,因为在与treeview交互之前,必须填充所有TreeItem->resourceEntry结构。