PDA

View Full Version : post event to QThread(Eventlool) from itself



TorAn
20th September 2016, 18:20
I have QThread-derived class (downloader) that has to download several files from the server sequentially. I post an event to the thread instance from main to start download, and then I am trying to post event to the thread (now a QEventLoop) for the next download. My question is: how to post the event from "within" the thread?


class T : public QThread
{
public:
void run() {
exec();
}
bool event (QEvent* event) {
//process download
...

//code breaks here. Question - how to post an event?
QApplication::instance()->postEvent(this, new userEvent());
}
}

int main()
{
T t;
t.start();
QApplication::instance()->postEvent(&t, new userEvent());
...
}

wysota
20th September 2016, 18:27
What you have will not work because you are posting an event to QThread object which does not live in the thread it represents. Instead your thread should have some QObject which you can post events to.

E.g.


QThread *thread = new QThread;
thread->start(); // implies exec()
DownloadHandler *handler = new DownloadHandler; // your object
handler->moveToThread(thread);
QApplication::postEvent(handler, new SomeEvent);

You can also use signals and slots, if you want.