Hi,
Does anyone know what has happened to QApplication:: postEvent and multithreading in Qt 4? If I post an event in another thread than the gui thread, the event is never handled.
Consider this minimal program:
#include <Qt/qapplication.h>
#include <Qt/qthread.h>
#include <iostream>
std::cerr << "Terminator::event" << std::endl;
return true;
}
};
int main(int argc, char** argv) {
std
::cerr <<
"main thread: " <<
QThread::currentThreadId() << std
::endl;
return app.exec();
}
#include <Qt/qapplication.h>
#include <Qt/qthread.h>
#include <iostream>
struct Terminator : QObject {
bool event(QEvent* event) {
std::cerr << "Terminator::event" << std::endl;
return true;
}
};
int main(int argc, char** argv) {
std::cerr << "main thread: " << QThread::currentThreadId() << std::endl;
QApplication app(argc, argv);
QApplication::postEvent(new Terminator,
new QEvent(QEvent::User));
return app.exec();
}
To copy to clipboard, switch view to plain text mode
A custom event that terminates the application is posted in the main loop. When QApplication::exec is called, the event is processed. Everything works as expected and the output is:
main thread: 140735005136720
Terminator::event
But if the event is posted in a different thread, it will not be handled. Here's a minimal thread class and accordingly adjusted main function:
void run() {
std::cerr << "MyThread: " << currentThreadId() << std::endl;
}
};
int main(int argc, char** argv) {
std
::cerr <<
"main thread: " <<
QThread::currentThreadId() << std
::endl;
MyThread mt;
mt.start();
return app.exec();
}
struct MyThread : QThread {
void run() {
std::cerr << "MyThread: " << currentThreadId() << std::endl;
QApplication::postEvent(new Terminator,
new QEvent(QEvent::User));
}
};
int main(int argc, char** argv) {
std::cerr << "main thread: " << QThread::currentThreadId() << std::endl;
QApplication app(argc, argv);
MyThread mt;
mt.start();
return app.exec();
}
To copy to clipboard, switch view to plain text mode
The output of the program is:
main thread: 139728441435984
MyThread: 1099274576
which means that Terminator::event is never called.
The system is a standard Fedora (2.6.27.5-41.fc9.x86_64) with pthreads. Everything worked in Qt 3, so somewhere along the way something has changed. Any clues?
Bookmarks