我正在尝试在单独的线程上填充QTreeView对象。我想写入的信息是网络驱动器上的文件夹+文件列表。迭代子目录需要花费很多时间,因此我不想在此操作期间阻止Gui线程。
这是我的代码:
class Worker : public QObject
{
Q_OBJECT
public slots:
void doWork(QString ¶meter){
QString data;
QDirIterator it(parameter, QStringList() << "*.xml", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
QString currentFile = it.next();
emit resultReady(currentFile);
}
}
signals:
void resultReady(QString &result);
};
class iUSMDatabaseComposerWindow:public QMainWindow{
Q_OBJECT
...
QThread workerThread;
QEventLoop loop;
public:
iUSMDatabaseComposerWindow(){
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
bool success = connect(&workerThread, SIGNAL(finished()), worker, SLOT(deleteLater())); assert(success);
success = connect(this, SIGNAL(getFilesInFolder(QString &)), worker, SLOT(doWork(QString &))); assert(success);
success = connect(worker, SIGNAL(resultReady(QString &)), this, SLOT(appendToTree(QString &))); assert(success);
//For Qt5 : connect( &workerThread, &QThread::started, &loop, &QEventLoop::quit );
success = connect( &workerThread, SIGNAL( started() ), &loop, SLOT( quit() ), Qt::DirectConnection ); assert(success);
workerThread.start();
loop.exec(); // wait for thread initialization
QString targetFolder (TARGETFOLDER);
emit getFilesInFolder(targetFolder);
}
signals:
void getFilesInFolder(QString &folderToProcess);
private slots:
void appendToTree(QString &file);
我遇到的是connect()是成功的但是工作人员的插槽(doWork)永远不会被emit getFilesInFolder(targetFolder)调用。我注意到如果我在连接到doWork()插槽时添加Qt :: DirectConnection,它会调用它。
这可能是什么问题?