Qt流程事件 [英] Qt process events
问题描述
我有一个QString
对象,该对象已导出到qml.在C++
代码中,在更新值并为该属性发出更改的信号时,它不会更新它,因为线程很忙:在那个时候,我在for循环中使用了成本操作.为此,我使用QCoreApplication::processEvents()
能够在循环的每次迭代中发出延迟信号,例如:
I have a QString
object which is exported to qml. In C++
code while updating the value and emitting the changed signal for the property it does not update it because thread is busy: in that time I use a cost-operation in for loop. For that purpose I use QCoreApplication::processEvents()
to be able to emit delayed signals on each iteration of the loop like:
foreach(const QVariant& item, _manifestFile) {
setStatusString(QString("Checking file %1 of %2...").arg(currentProcessingFile++).arg(totalFilesCount));
QCoreApplication::processEvents(); // TODO remove
//...
}
setStatusString
是上述我的QString
变量的设置器:
Where setStatusString
is setter of my QString
variable I described above:
void Updater::setStatusString(const QString &statusString) {
_statusString = statusString;
emit statusStringChanged();
}
如何删除该processEvents()
并能够发出信号?任何解决方案都值得赞赏:线程,Qt-meta对象等等.
How can I remove that processEvents()
and be able to emit signals? Any solution is appreciated: threaded, Qt-meta object things, etc.
推荐答案
您应该在堆上创建类Updater
的对象,然后将其移动到新线程中,以防止for循环阻塞主线程和用户界面.可以这样完成:
You should create your object of the class Updater
on the heap and move it to a new thread in order to prevent the for loop from blocking main thread and the UI. This can be done like:
updater = new Updater();
QThread * th = new QThread();
updater->moveToThread(th);
QObject::connect(th,SIGNAL(started()),updater,SLOT(OnStarted()));
QObject::connect(th,SIGNAL(finished()),updater,SLOT(OnFinished()));
QObject::connect(updater,SIGNAL(statusStringChanged(QString)),this,SLOT(updateString(QString)));
th->start();
您在Updater
类中的初始化和终止任务应分别在OnStarted()
和OnFinished()
插槽中完成.
Your initialization and termination tasks in the class Updater
should be done in OnStarted()
and OnFinished()
slots respectively.
现在,您可以发出具有适当值的信号,该信号将在适当的时间排队和处理.您可以按一定的时间间隔定期在计时器中发射信号,以防止发射频率太高.
Now you can emit the signal with the appropriate value which would be queued and processed in the appropriate time. You can emit the signal in a timer periodically in certain intervals to prevent from emitting too frequent.
最后一点是,当它不在另一个线程中时,您不应直接调用Updater
函数.正确的方法是将功能定义为插槽,并在要调用特定功能时将信号连接到该插槽并发出信号.
And the last point is that you should not call Updater
functions directly when it is in an other thread. The correct way is defining the functions as slots and connecting a signal to that slot and emitting the signal when you want to call a specific function.
这篇关于Qt流程事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!