Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to handle a QTimer from another Thread in the MainWindow Class with a Connection and Signal and Slot ->QueuedConnection
Qt 6.11 is out! See what's new in the release blog

How to handle a QTimer from another Thread in the MainWindow Class with a Connection and Signal and Slot ->QueuedConnection

Scheduled Pinned Locked Moved Solved General and Desktop
22 Posts 4 Posters 12.2k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • mrjjM mrjj

    Hi
    Cant you just connect the mainwindow signal to the Simulator in mainwindow ?
    No need to pass the mainwindow and let Simulator connect if mainwindow knows simulator.

    So when you create Simulator
    (pseudo code)
    Simulator * new Simulator ()
    connect(Simulator , SimulatorSignal , this , slotinmainwindow, qt::QueuedConnection ); // note QueuedConnection

    or did i miss something ?

    K Offline
    K Offline
    KonradMD
    wrote on last edited by
    #4

    @mrjj
    @SGaist

    I thought the same, I tried it with emitting a signal in my own MainWindow::stop Method and connecting it to the stop method in the Simulator. Currently it is handled:

    hegDevice           = new HEGSimulator();
    
    connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
       connect(ui->stopbutton,             SIGNAL(clicked()),this,         SLOT(stop()));
    
    void MainWindow::stop()
    {
    //    hegDevice->stopDevice();
     //thread->quit();
    }
    

    I toggled and untoggeled everythinh in these methods, still getting the same errors...

    QueuedConnection and Direct Connection are resulting the same Output:

    After pushing the stop button:

    
    QObject::killTimer: Timers cannot be stopped from another thread
    Stopped worker process in Thread  0x15b8
    

    After closing the window:

    
    QObject::~QObject: Timers cannot be stopped from another thread
    

    @mrjj case would have a signal from the simulator, but I just get the signal from pushing the stop button.
    @SGaist
    Your first connect is also with a signal from the simulator. But the timer is in the 2nd thread in the simulator file. So I can just stop it in a method in this class?!

    Maybe I am stuck in my brain somewhere. Feels like ..

    K 1 Reply Last reply
    0
    • K KonradMD

      @mrjj
      @SGaist

      I thought the same, I tried it with emitting a signal in my own MainWindow::stop Method and connecting it to the stop method in the Simulator. Currently it is handled:

      hegDevice           = new HEGSimulator();
      
      connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
         connect(ui->stopbutton,             SIGNAL(clicked()),this,         SLOT(stop()));
      
      void MainWindow::stop()
      {
      //    hegDevice->stopDevice();
       //thread->quit();
      }
      

      I toggled and untoggeled everythinh in these methods, still getting the same errors...

      QueuedConnection and Direct Connection are resulting the same Output:

      After pushing the stop button:

      
      QObject::killTimer: Timers cannot be stopped from another thread
      Stopped worker process in Thread  0x15b8
      

      After closing the window:

      
      QObject::~QObject: Timers cannot be stopped from another thread
      

      @mrjj case would have a signal from the simulator, but I just get the signal from pushing the stop button.
      @SGaist
      Your first connect is also with a signal from the simulator. But the timer is in the 2nd thread in the simulator file. So I can just stop it in a method in this class?!

      Maybe I am stuck in my brain somewhere. Feels like ..

      K Offline
      K Offline
      KonradMD
      wrote on last edited by KonradMD
      #5

      Crazy stuff, now it works for the push button

      connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
      
      connect(ui->stopbutton,             SIGNAL(clicked()),this,         SLOT(stop()));
      
      void MainWindow::stop()
      {
       thread->quit();
      }
      

      closing the window causes still:

      QObject::killTimer: Timers cannot be stopped from another thread
      QObject::~QObject: Timers cannot be stopped from another thread
      

      but I guess I need to implement some stuff in the destructor

      1 Reply Last reply
      0
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #6

        Where are you creating that timer exactly ?

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        K 1 Reply Last reply
        2
        • SGaistS SGaist

          Where are you creating that timer exactly ?

          K Offline
          K Offline
          KonradMD
          wrote on last edited by
          #7

          @SGaist

          HEGSimulator::HEGSimulator()
          {
              _pSample    =   new Sample();
          
              _samplerate =   10;
              _xData      =   0;
              _yData      =   0;
              _iTrianglefunction=0;
          
          }
          
          HEGSimulator::~HEGSimulator()
          {
           delete _timer;
              delete _pSample;
          }
          
          void HEGSimulator::startDevice()
          {
              _timer      =   new QTimer();
               connect(_timer, SIGNAL(timeout()),this,SLOT(createSample()));
          
          //  _timer->moveToThread(this->thread()); //doesnot work so implemented in this method
              _timer->start(_samplerate);
              qDebug()<<"Starting worker process in Thread "<<thread()->currentThreadId();
          
          }
          
          1 Reply Last reply
          0
          • SGaistS Offline
            SGaistS Offline
            SGaist
            Lifetime Qt Champion
            wrote on last edited by
            #8

            Where/when is startDevice called ?

            Interested in AI ? www.idiap.ch
            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

            K 1 Reply Last reply
            2
            • SGaistS SGaist

              Where/when is startDevice called ?

              K Offline
              K Offline
              KonradMD
              wrote on last edited by
              #9

              @SGaist
              Thanks for helping me:

              hegDevice           = new HEGSimulator();
              thread              = new QThread();
              thread->setObjectName("SIMULATOR");
              
              connect(ui->startButton,            SIGNAL(clicked()),this,         SLOT(start()));
              connect(thread,                     SIGNAL(started()),hegDevice,                SLOT(startDevice()),Qt::DirectConnection);
              connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
                  connect(ui->stopbutton,             SIGNAL(clicked()),thread,       SLOT(quit()),Qt::QueuedConnection);
              
              MainWindow::~MainWindow()
              {
              //does not  work properly
                  thread->quit();
                  hegDevice->stopDevice();
                  delete hegDevice;
              
              }
              void MainWindow::start()
              {
                  /**
                  (1) Start the hegDevice in its own Thread to let it run on their own.
                  **/
              hegDevice->moveToThread(thread);                                         //(1)
                  thread->start();
                  qDebug()<<"MainThread "<<this->QObject::thread()->currentThreadId();
              }
              

              AND the stop out of heg simulator

              void HEGSimulator::stopDevice()
              {
                  _timer->stop();
              
                  qDebug()<<"Stopped worker process in Thread "<<thread()->currentThreadId();
              
              }
              
              J.HilkJ 1 Reply Last reply
              1
              • K KonradMD

                @SGaist
                Thanks for helping me:

                hegDevice           = new HEGSimulator();
                thread              = new QThread();
                thread->setObjectName("SIMULATOR");
                
                connect(ui->startButton,            SIGNAL(clicked()),this,         SLOT(start()));
                connect(thread,                     SIGNAL(started()),hegDevice,                SLOT(startDevice()),Qt::DirectConnection);
                connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
                    connect(ui->stopbutton,             SIGNAL(clicked()),thread,       SLOT(quit()),Qt::QueuedConnection);
                
                MainWindow::~MainWindow()
                {
                //does not  work properly
                    thread->quit();
                    hegDevice->stopDevice();
                    delete hegDevice;
                
                }
                void MainWindow::start()
                {
                    /**
                    (1) Start the hegDevice in its own Thread to let it run on their own.
                    **/
                hegDevice->moveToThread(thread);                                         //(1)
                    thread->start();
                    qDebug()<<"MainThread "<<this->QObject::thread()->currentThreadId();
                }
                

                AND the stop out of heg simulator

                void HEGSimulator::stopDevice()
                {
                    _timer->stop();
                
                    qDebug()<<"Stopped worker process in Thread "<<thread()->currentThreadId();
                
                }
                
                J.HilkJ Offline
                J.HilkJ Offline
                J.Hilk
                Moderators
                wrote on last edited by
                #10

                @KonradMD
                With direct connection, the slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.

                So my guess with:

                connect(thread,  SIGNAL(started()),hegDevice, SLOT(startDevice()),Qt::DirectConnection);
                

                you're actually creating the timer in the main thread.

                try it with Qt::QueuedConnection


                Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                Q: What's that?
                A: It's blue light.
                Q: What does it do?
                A: It turns blue.

                K 1 Reply Last reply
                2
                • J.HilkJ J.Hilk

                  @KonradMD
                  With direct connection, the slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.

                  So my guess with:

                  connect(thread,  SIGNAL(started()),hegDevice, SLOT(startDevice()),Qt::DirectConnection);
                  

                  you're actually creating the timer in the main thread.

                  try it with Qt::QueuedConnection

                  K Offline
                  K Offline
                  KonradMD
                  wrote on last edited by KonradMD
                  #11

                  @J.Hilk

                  Right now, the connects are working I guess, but I will test your advice. If I stop the Measurement before Closing the window I get:

                  MainThread  0x160c
                  Starting worker process in Thread  0x150c
                  Stopped worker process in Thread  0x150c
                  Stopped worker process in Thread  0x160c
                  

                  The last line is not cool, its because of the destructor code but no Qt Message in comparison to:

                  If I close the window before pressing stop:

                  MainThread  0x14d4
                  Starting worker process in Thread  0x12f8
                  QObject::killTimer: Timers cannot be stopped from another thread
                  Stopped worker process in Thread  0x14d4
                  QObject::~QObject: Timers cannot be stopped from another thread
                  
                  

                  @J-Hilk
                  Your Advice with Queued Connection results in the same application output. And the _timer is in the same thread with both methods. I read that Direct is immediatly calling the slot and Queued is waiting until the normal Code is finished? So probably its risky to use direct because I dont know if the class is already moved in the thread? is that what you mentioned?

                  1 Reply Last reply
                  0
                  • SGaistS Offline
                    SGaistS Offline
                    SGaist
                    Lifetime Qt Champion
                    wrote on last edited by
                    #12

                    Give your QTimer a parent. That way it will be moved with the worker object when calling moveToThread.

                    Interested in AI ? www.idiap.ch
                    Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                    1 Reply Last reply
                    3
                    • K Offline
                      K Offline
                      KonradMD
                      wrote on last edited by KonradMD
                      #13

                      Hey @SGaist

                      I set the HEGSimulator as parent from my _timer. And replaced the timer and the connecter in the constructor. I used _timer->moveToThread(this->thread()) to move the _timer to the Thread I am using for the class, this should work, if I interpret the output correctly. But there is a new error message and I guess its something with my emit from the main in the end. I can not figure out where exactly its placed. But it is just there, if I close te GUI.

                      _timer      =   new QTimer(this);
                      
                      ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 1b7e7ca0. Receiver '' (of type 'HEGSimulator') was created in thread 1b87f408", file kernel\qcoreapplication.cpp, line 541
                      Invalid parameter passed to C runtime function.
                      Invalid parameter passed to C runtime function.
                      
                      1 Reply Last reply
                      0
                      • SGaistS Offline
                        SGaistS Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on last edited by
                        #14

                        You seem to have several timers in your code, which one are you moving exactly ?

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        K 1 Reply Last reply
                        1
                        • SGaistS SGaist

                          You seem to have several timers in your code, which one are you moving exactly ?

                          K Offline
                          K Offline
                          KonradMD
                          wrote on last edited by
                          #15

                          @SGaist

                          In my Simulator class I have just one timer for the Samplerate of my Data. In the MainWindow I have a Timer as well for my framerate, but I want to get rid of it, but it is also a problem... I am not that into QThreads right now, maybe I should read some tutorials about it again.

                          Would you initialise the Timers in the Main Window and move them to the thread and controll the connections in main window instead of directly in the class?

                          Thanks for your advices!

                          1 Reply Last reply
                          0
                          • SGaistS Offline
                            SGaistS Offline
                            SGaist
                            Lifetime Qt Champion
                            wrote on last edited by
                            #16

                            It really depends on how you manage your thread.

                            The current Qt 5 documentation about QThread is way better than before so it should help you get on track.

                            Interested in AI ? www.idiap.ch
                            Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                            1 Reply Last reply
                            2
                            • K Offline
                              K Offline
                              KonradMD
                              wrote on last edited by
                              #17

                              I think this case can be marked as solved, I really dont understand the syntax completly, because I have a similar case now, more complex, but also a QTimer which should start and I always get the same Error-Message. I hope that with some time for trail and error I will understand the syntax. My solution for this case is:

                              MainWindow::MainWindow()
                              {
                                  hegDevice           = new HEGSimulator();
                                  simulatorThread     = new QThread();
                              
                                  connect(simulatorThread,            SIGNAL(started()),hegDevice,                SLOT(startDevice()),Qt::QueuedConnection);
                              
                               connect (this,SIGNAL(stopHEGDevice()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
                              
                               connect(ui->startButton,            SIGNAL(clicked()),this,         SLOT(start()));
                                  connect(ui->stopbutton,             SIGNAL(clicked()),hegDevice,    SLOT(stopDevice()),Qt::QueuedConnection);
                                  connect(ui->stopbutton,             SIGNAL(clicked()),simulatorThread,       SLOT(quit()),Qt::QueuedConnection);
                              
                              }
                              
                              void MainWindow~MainWindow
                              {
                               if(simulatorThread->isRunning())
                                  {
                                      emit stopHEGDevice();
                                      //because of the delation of the emit I use this msleep. Debug Mode works properly without Debug the simulatorThread->quit was faster than the emit.
                                      this->thread()->msleep(100);
                              
                              delete hegDevice;
                                  }
                              
                                  //Out of Qt Docu
                                  simulatorThread->quit();
                                  simulatorThread->wait();
                              }
                              
                              void MainWindow::start()
                              {
                              qDebug()<<"MainThread "<<this->QObject::thread()->currentThreadId();
                              
                                  hegDevice->moveToThread(simulatorThread);                                     
                                  simulatorThread->start();
                              }
                              
                              HEGSimulator::HEGSimulator()
                              {}
                              
                              HEGSimulator::~HEGSimulator
                              {
                              delete _timer;
                              }
                              
                              void HEGSImulator::startDevice()
                              {
                              _timer      =   new QTimer();
                                   connect(_timer, SIGNAL(timeout()),this,SLOT(createSample()));
                                  _timer->start(_samplerate);
                                  qDebug()<<"Starting HEGDevice in Thread: "<<thread()->currentThreadId();
                              }
                              
                              void HEGSimulator::stopDevice()
                              {
                               _timer->stop();
                                  qDebug()<<"Stopped HEGDevice in Thread: "<<thread()->currentThreadId();
                              }
                              

                              In every case I can imagine the output is:

                              MainThread  0x1754
                              Starting HEGDevice in Thread:  0x63c
                              Stopped HEGDevice in Thread:  0x63c
                              
                              1 Reply Last reply
                              0
                              • SGaistS Offline
                                SGaistS Offline
                                SGaist
                                Lifetime Qt Champion
                                wrote on last edited by
                                #18

                                You realise that each time you call startDevice you create a new QTimer and you only delete the last one created in your HEGSimulator destructor.

                                Either create your timer in the constructor of HEGSimulator giving this as parent or check if the _timer already exist before creating a new one in startDevice. When an QObject is moved to another thread all its children are moved with it.

                                Interested in AI ? www.idiap.ch
                                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                                K 1 Reply Last reply
                                2
                                • SGaistS SGaist

                                  You realise that each time you call startDevice you create a new QTimer and you only delete the last one created in your HEGSimulator destructor.

                                  Either create your timer in the constructor of HEGSimulator giving this as parent or check if the _timer already exist before creating a new one in startDevice. When an QObject is moved to another thread all its children are moved with it.

                                  K Offline
                                  K Offline
                                  KonradMD
                                  wrote on last edited by
                                  #19

                                  @SGaist

                                  I realised it, and you are right, it is not resource friendly. I changed it, and its working as well. Just quiting the main window causes some Errors.

                                  ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 1b6d7ca0. Receiver '' (of type 'HEGSimulator') was created in thread 1b772990", file kernel\qcoreapplication.cpp, line 541
                                  Invalid parameter passed to C runtime function.
                                  Invalid parameter passed to C runtime function.
                                  

                                  I will fix that and update this thread, I guess my mistake is something with quiting the thread, because the HEGDevice is already stopped.
                                  Just beside, is my MainWindow Start function right and does this connecter make sense?

                                  connect(ui->stopbutton,             SIGNAL(clicked()),simulatorThread,       SLOT(quit()),Qt::QueuedConnection);
                                  
                                  MainThread  0x14dc
                                  Starting HEGDevice in Thread:  0x17e0
                                  Stopped HEGDevice in Thread:  0x17e0
                                  MainThread  0x14dc
                                  Starting HEGDevice in Thread:  0x1620
                                  Stopped HEGDevice in Thread:  0x1620
                                  

                                  it looks like I created a new thread...?! I just wanted to stop the current one and let it wait until a new work is incoming. Or is it better to stop them and recreate?

                                  I am a little bit confused, because I just created a Pointer named simulatorThread and if I quit this one, a new one is coming out of nowhere?
                                  Can you help me to understand or give me some advice :)

                                  Thanks in advance :)

                                  J.HilkJ 1 Reply Last reply
                                  0
                                  • K KonradMD

                                    @SGaist

                                    I realised it, and you are right, it is not resource friendly. I changed it, and its working as well. Just quiting the main window causes some Errors.

                                    ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 1b6d7ca0. Receiver '' (of type 'HEGSimulator') was created in thread 1b772990", file kernel\qcoreapplication.cpp, line 541
                                    Invalid parameter passed to C runtime function.
                                    Invalid parameter passed to C runtime function.
                                    

                                    I will fix that and update this thread, I guess my mistake is something with quiting the thread, because the HEGDevice is already stopped.
                                    Just beside, is my MainWindow Start function right and does this connecter make sense?

                                    connect(ui->stopbutton,             SIGNAL(clicked()),simulatorThread,       SLOT(quit()),Qt::QueuedConnection);
                                    
                                    MainThread  0x14dc
                                    Starting HEGDevice in Thread:  0x17e0
                                    Stopped HEGDevice in Thread:  0x17e0
                                    MainThread  0x14dc
                                    Starting HEGDevice in Thread:  0x1620
                                    Stopped HEGDevice in Thread:  0x1620
                                    

                                    it looks like I created a new thread...?! I just wanted to stop the current one and let it wait until a new work is incoming. Or is it better to stop them and recreate?

                                    I am a little bit confused, because I just created a Pointer named simulatorThread and if I quit this one, a new one is coming out of nowhere?
                                    Can you help me to understand or give me some advice :)

                                    Thanks in advance :)

                                    J.HilkJ Offline
                                    J.HilkJ Offline
                                    J.Hilk
                                    Moderators
                                    wrote on last edited by
                                    #20

                                    @KonradMD
                                    Let me ask you, why do you want to "pause" the Thread and pick it up later again?

                                    From what I understood of your previous posts, you used the Worker approach, that means when your Threaded obejcts/classes have nothing to do the QThread will take up - next to- no ressources.


                                    Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                    Q: What's that?
                                    A: It's blue light.
                                    Q: What does it do?
                                    A: It turns blue.

                                    K 1 Reply Last reply
                                    2
                                    • J.HilkJ J.Hilk

                                      @KonradMD
                                      Let me ask you, why do you want to "pause" the Thread and pick it up later again?

                                      From what I understood of your previous posts, you used the Worker approach, that means when your Threaded obejcts/classes have nothing to do the QThread will take up - next to- no ressources.

                                      K Offline
                                      K Offline
                                      KonradMD
                                      wrote on last edited by
                                      #21

                                      @J.Hilk

                                      I thought that it will still took some CPU. But indeed you are right, I just let it run, with nothing to do, because I stopped the qtimer.

                                      I changed that, Thanks :)

                                      1 Reply Last reply
                                      0
                                      • K Offline
                                        K Offline
                                        KonradMD
                                        wrote on last edited by KonradMD
                                        #22

                                        I get this Error,

                                        ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread edad48. Receiver '' (of type 'HEGSimulator') was created in thread 1bc55888", file kernel\qcoreapplication.cpp, line 541
                                        Invalid parameter passed to C runtime function.
                                        Invalid parameter passed to C runtime function.
                                        

                                        just in Debug Mode and exactly when I want to

                                        delete hegDevice;
                                        

                                        in which the Thread was running.

                                        My solution for that is:

                                        connect(simulatorThread,SIGNAL(finished()),hegDevice,SLOT(deleteLater()));
                                        

                                        and no

                                        delete hegDevice
                                        

                                        in the Destructor anymore

                                        1 Reply Last reply
                                        0

                                        • Login

                                        • Login or register to search.
                                        • First post
                                          Last post
                                        0
                                        • Categories
                                        • Recent
                                        • Tags
                                        • Popular
                                        • Users
                                        • Groups
                                        • Search
                                        • Get Qt Extensions
                                        • Unsolved