Ale*_*exP 7 qt multithreading event-loop qthread qt5
调用QCoreApplication::hasPendingEvents()或QAbstractEventDispatcher::instance()->hasPendingEvents()在线程内部工作正常.但是,在它之外,后者(具有适当的参数)总是返回false(前者不能在外部使用,因为它指的是从中调用它的线程).
这是一个完整的代码:
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
#include <QThread>
#include <QDebug>
bool hasPendingEvents(QThread *thread = 0) {
return QAbstractEventDispatcher::instance(thread)->hasPendingEvents();
}
class MyObject: public QObject {
Q_OBJECT
public slots:
void Run() {
qDebug() << __LINE__ << hasPendingEvents() << QCoreApplication::hasPendingEvents();
QThread::sleep(1);
}
};
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QThread thread;
MyObject t;
t.moveToThread(&thread);
thread.start();
for (int i = 0; i<4; ++i) QMetaObject::invokeMethod(&t, "Run", Qt::QueuedConnection);
for (int i = 0; i<10; ++i) {
QThread::msleep(500);
qDebug() << __LINE__ << hasPendingEvents(&thread) << hasPendingEvents(t.thread());
}
return 0;
}
#include "main.moc"
Run Code Online (Sandbox Code Playgroud)
这是输出:
15 true true
31 false false
31 false false
15 true true
31 false false
31 false false
15 true true
31 false false
31 false false
15 false false
31 false false
31 false false
31 false false
31 false false
Run Code Online (Sandbox Code Playgroud)
为什么不在QAbstractEventDispatcher.hasPendingEvents()线程外工作?也许有另一种选择?
| 归档时间: |
|
| 查看次数: |
1790 次 |
| 最近记录: |