1

I try to start QTimer from another thread ( to get better accuracy ).

I think that problem is with function connect but let see my code:

//code from constructor of parent.cpp class
{
    //run_clock_timer(this); // this works

    std::thread t1{ [this] { run_clock_timer(this); } }; //not works
    t1.join();
}

And function:

void class::run_clock_timer(class* inst){
    QTimer * test = new QTimer(inst);
    connect(test, SIGNAL(timeout()), inst, SLOT(updateTime()));
    test->setInterval(50);
    test->start(timer_precision);
}

Debugger told me that code from run_clock_timer was run, but no result.

I think i will do it with no problem when i use QThread, but i want to use std::thread.

So whats wrong with my function ?

Thomas Banderas
  • 1,681
  • 1
  • 21
  • 43
  • 1
    Why do you want to use STL thread? How are you starting the event loop in that thread? – MrEricSir Aug 06 '14 at 02:02
  • 1
    This is apossible duplicate of [QMetaObject::invokeMethod doesn’t work when…](http://stackoverflow.com/questions/10356343/qmetaobjectinvokemethod-doesn-t-work-when). The answer to that question has the code you're looking for. – Kuba hasn't forgotten Monica Aug 07 '14 at 01:25

1 Answers1

2

The problem is that QTimer depends on the ability to interact with a running Qt event loop in order to perform its task. Since a non-Qt thread has no event loop, the QTimer can't do its job. (i.e. there has to be some Qt code running in the thread, that will emit the timeout() signal, that doesn't just happen on its own)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • So can you give a example code what i have to add to this thread? Code which is not invasive (i.e for ex. dont add new window ) – Thomas Banderas Aug 06 '14 at 12:28
  • AFAIK your choices are either use a QThread, or use some other timing mechanism besides QTimer. Or possibly you could declare a QEventLoop object in your thread and call exec() on it; I've never tried it though so I don't know if that works correctly or not. – Jeremy Friesner Aug 06 '14 at 15:55