[Interest] BUG? QTimer in QThread

André Somers andre at familiesomers.nl
Tue May 13 13:34:15 CEST 2014


Sensei schreef op 13-5-2014 13:24:
> Dear all,
>
> I am reporting this weird behavior because I believe it could be a
> potential bug: my code is too simple to have an unexpected behavior.
>
> Anyway *BEWARE*: I might be making a huge mistake in my code that I
> don't see! Please forgive me if I am wrong! :)
>
> So, here I go.
>
>
> I have a class that I move to a thread. Each X millisecond, I need to
> run a method, and this is done with a QThread. However, it wasn't
> working and I didn't know why. The slot wasn't called by the timeout()
> connection.
>
> After one day, I decided the only possible culprit could be the thread,
> and... AHA! It works!
>
> Now, can anyone spot my mistake? I assume it's my fault, and not Qt's
> since they saved me so many times! :)
>
>
> The class is created this way in my QMainWindow:
>
>           inThreadThread_ = new QThread(this);
>           inThread_ = new myClass();
>           inThread_->moveToThread(inThreadThread_);
>
>
>
>
> And the class is as follows:
>
>
>
> class myClass : public QObject
> {
>       // ...
> public slots:
>
>       void dummy() { qWarning("timer in thread"); };
>
>       // ...
>
> private:
>
>       QTimer *inThread_;
> }
>
>
> myClass::myClass() : QObject(NULL)
> {
>       // ...
>       inThread_ = new QTimer(this);
>       connect(inThread_, SIGNAL(timeout()), this, SLOT(dummy()));
>       inThread_->start(1000);
> }
>
>
>
> Note that if I comment the thread-related parts in the main window, and
> I just create a new object, the dummy slot is called without a hiccup.
> When uncommenting the new QThread and the moveToThread lines, no timed
> slot execution.
>
> For complete information, I am using Qt 4.8.6 (from Homebrew) on a MacOS
> X 10.9.2.
>
>
> What am I doing wrong in my code?
>
>
I think the root of your problem may be that you are starting your timer 
from the constructor of myClass, and then move the instance of myClass 
to a thread. What happens if you do something like this?

Q_SLOT myClass::start()
{
      inThread_ = new QTimer(this);
      connect(inThread_, SIGNAL(timeout()), this, SLOT(dummy()));
      inThread_->start(1000);
}

The class is created this way in my QMainWindow:

inThreadThread_ = new QThread(this);
inThread_ = new myClass();
connect(inThreadThread, SIGNAL(started()), inThread_, SLOT(start()));
inThread_->moveToThread(inThreadThread_);
inThreadThread->start();


HTH,

André

  





More information about the Interest mailing list