问题
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
//...
}
Where setStatusString
is setter of my QString
variable I described above:
void Updater::setStatusString(const QString &statusString) {
_statusString = statusString;
emit statusStringChanged();
}
How can I remove that processEvents()
and be able to emit signals? Any solution is appreciated: threaded, Qt-meta object things, etc.
回答1:
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();
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.
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.
来源:https://stackoverflow.com/questions/27856307/qt-process-events