|
|
Source code |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
class DLLEXPORT Worker: public QObject
{
Q_OBJECT
Worker()
{
QObject::connect(&_timer,SIGNAL(timeout()),this,SLOT(doWork()));
long id=(long)QThread::currentThreadId();
}
~Worker();
signals:
void Changed(const Data&);
public slots:
void start()
{
//the program does reach here
_timer.start(1000);
}
void doWork()
{
//The problem is this never get called!! Even though i have started the timer in start() func above
}
void stop()
{
//this is called when i clicked my UI push button
}
private:
QTimer _timer;
};
In a separate GUI application:
qmain::qmain(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
QThread *pThread= new QThread;
Worker*worker= new Worker;
QObject::connect(ui.pushButton, SIGNAL(clicked()),worker, SLOT(stop()));
worker->connect(pThread,SIGNAL(started()),SLOT(start()));
worker->moveToThread(pThread); //Everything works if i commented out this line. But i guess this is not what i want, as i want the doWork to be done in separate thread.
pThread->start();
long id=(long)QThread::currentThreadId();
}
|
This post has been edited 1 times, last edit by "mce" (Jun 1st 2012, 5:45am)
|
|
Source code |
1 2 3 4 5 6 |
worker->moveToThread(pThread); QObject::connect(ui.pushButton, SIGNAL(clicked()),worker, SLOT(stop())); worker->connect(pThread,SIGNAL(started()),SLOT(start())); pThread->start(); |
|
|
Source code |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public slots:
void start()
{
while(!stop)
{
doWork();
SleepThread::msleep(2000);
}
}
void doWork()
{
.....
}
//the following doesn't get invoked when ui pushbutton is clicked.
void stop()
{
stop=true;
//this should be called when i clicked my UI push button
}
|
I was right with my first post to be suspicious of that QTimer being created in one thread but used in another.|
|
Source code |
1 2 3 4 5 |
Worker::Worker() :
_timer(this)
{
QObject::connect(&_timer,SIGNAL(timeout()),this,SLOT(doWork()));
}
|
|
|
Source code |
1 2 |
_timer.thread()? QThread::thread()?? |
|
|
Source code |
1 2 |
Worker::Worker() : _timer(/*this*/)
{ QObject::connect(&_timer,SIGNAL(timeout()),this,SLOT(doWork())); }
|
|
|
Source code |
1 2 3 4 5 6 7 8 9 10 |
void start()
{
//id1 and id2 always the same regardless _timer initialization with "this" or not
long id1=(long)_timer.thread()->currentThreadId();
long id2=(long)QThread::currentThreadId();
//the program does reach here
_timer.start(1000);
}
|
This post has been edited 2 times, last edit by "mce" (Jul 3rd 2012, 10:08am)