Is it not possible to post custom events (across thread) to a QThread descendant? Or am I doing something wrong? Should I create a child for the thread and post events to the child object to get events delivered to the correct thread?
The code below illustrates the problem:
#include <QtGui>
#include <QtDebug>
{
public:
{
}
protected:
void run()
{
qDebug
() <<
"MyThread::run()" <<
QThread::currentThread() << this
->thread
();
exec();
}
void customEvent
(QEvent* event
) {
qDebug
() <<
"MyThread::customEvent()" <<
QThread::currentThread() << this
->thread
();
// a long loop here will naturally block GUI
qDebug() << "LOOP BEGIN";
for (uint i = 0; i < -1; ++i);
qDebug() << "LOOP END";
}
};
{
Q_OBJECT
public:
{
mythread = new MyThread(this); // creating without parent has no effect
mythread->start();
connect(this, SIGNAL(clicked()), this, SLOT(postEvent()));
}
private slots:
void postEvent()
{
qDebug
() <<
"EventButton::postEvent()" <<
QThread::currentThread() << this
->thread
();
}
private:
MyThread* mythread;
};
int main(int argc, char *argv[])
{
qDebug
() <<
"main()" <<
QThread::currentThread();
EventButton b;
b.show();
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
return a.exec();
}
#include "main.moc"
#include <QtGui>
#include <QtDebug>
class MyThread : public QThread
{
public:
MyThread(QObject* parent = 0) : QThread(parent)
{
}
protected:
void run()
{
qDebug() << "MyThread::run()" << QThread::currentThread() << this->thread();
exec();
}
void customEvent(QEvent* event)
{
qDebug() << "MyThread::customEvent()" << QThread::currentThread() << this->thread();
// a long loop here will naturally block GUI
qDebug() << "LOOP BEGIN";
for (uint i = 0; i < -1; ++i);
qDebug() << "LOOP END";
}
};
class EventButton : public QPushButton
{
Q_OBJECT
public:
EventButton() : QPushButton("Post an event")
{
mythread = new MyThread(this); // creating without parent has no effect
mythread->start();
connect(this, SIGNAL(clicked()), this, SLOT(postEvent()));
}
private slots:
void postEvent()
{
qDebug() << "EventButton::postEvent()" << QThread::currentThread() << this->thread();
QApplication::postEvent(mythread, new QEvent(QEvent::User));
}
private:
MyThread* mythread;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug() << "main()" << QThread::currentThread();
EventButton b;
b.show();
a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
return a.exec();
}
#include "main.moc"
To copy to clipboard, switch view to plain text mode
Please, spot a mistake there..
Bookmarks