Hi guys!
I have the following problem:
1. I want get thread doing some work and update the label in the main thread every second.
2. I got it working subclassing QThread bu according to some sources it is not a good way.
3. I decided to subclass a QObject (MyObject) with internal QTimer* _myTimer, and doWork() function with an internal loop, This object is after construction moved to newly created QThread* _thread.
My problem is that _myTimer's timeout() signal which is connected to tick() slot of the _myObject, is not executed after _thread->start(). tick() is executed only after doing _thread->wait(). Both the tick() slot and myTimer exist in the myThread so i do not know what is the problem. It seems like there is no event loop in myThread.
Here is my code:
{
Q_OBJECT
public:
public slots:
void tick();
void doWork();
private:
};
void MyObject::doWork()
{
_myTimer->setInterval(1000);
connect(_myTimer, SIGNAL(timeout()), this, SLOT(tick())/*,Qt::DirectConnection*/);
_myTimer->start()
qDebug
() <<
QThread::currentThreadId() <<
"doWork()";
while(..)
{
...
}
}
void MyObject::tick()
{
emit tickSignalToGUI(..);
qDebug
() <<
QThread::currentThreadId() <<
"tick()";
}
// and somewhere in GUI thread
(...)
_myObject = new MyObject(); /
_myObject->moveToThread(_thread);
_thread->start();
// _myObject->doWork(); //this blocks execution
qDebug
() <<
QThread::currentThreadId() <<
"GUI thread";
(...)
class MyObject : QObject
{
Q_OBJECT
public:
MyObject(QObject *parent=0);
public slots:
void tick();
void doWork();
private:
QTimer* _myTimer;
};
void MyObject::doWork()
{
_myTimer = new QTimer(this);
_myTimer->setInterval(1000);
connect(_myTimer, SIGNAL(timeout()), this, SLOT(tick())/*,Qt::DirectConnection*/);
_myTimer->start()
qDebug() << QThread::currentThreadId() << "doWork()";
while(..)
{
...
}
}
void MyObject::tick()
{
emit tickSignalToGUI(..);
qDebug() << QThread::currentThreadId() << "tick()";
}
// and somewhere in GUI thread
(...)
_thread = new QThread(this);
_myObject = new MyObject(); /
_myObject->moveToThread(_thread);
_thread->start();
// _myObject->doWork(); //this blocks execution
QMetaObject::invokeMethod(_myObject,"doWork");
qDebug() << QThread::currentThreadId() << "GUI thread";
(...)
To copy to clipboard, switch view to plain text mode
Any ideas what is wrong with this approach?
best regards,
Bookmarks