Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved QThread, signals and lambdas

    General and Desktop
    3
    4
    621
    Loading More Posts
    • 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.
    • J
      Jeff Barnes last edited by

      It took me a while to figure out that this causes a crash. Linguistically, it is opaque to me. Could someone please tell me why this isn't good, please?

      MyClass::MyClass
          :   QWidget()
          ,   myObject(new MyObject)
      {
          // Causes memory corruption, intermittent crashes, QTimer warnings, etc.
      //    QObject::connect(myObject, MyObject::mySignal, []() {
      //        QMessageBox mb;
      //        mb.setText("Hello world");
      //        mb.exec();
      //    });
          //this works fine
          QObject::connect(myObject, MyObject::mySignal, this, &MyClass::handleMySignal);
          QThread *thr = new QThread;
          QObject::connect(myObject, MyObject::destroyed, thr, QThread::quit);
          QObject::connect(thr, &QThread, &QThread::finished, thr, &QThread::deleteLater);
          myObject->moveToThread(thr);
          thr->start();
      }
      
      void MyClass::handleMySignal()
      {
          QMessageBox mb;
          mb.setText("Hello world");
          mb.exec();
      }
      
      
      KroMignon 1 Reply Last reply Reply Quote 0
      • Christian Ehrlicher
        Christian Ehrlicher Lifetime Qt Champion last edited by

        This is because the lambda version is executed in the thread, not in the main thread which is not allowed for gui operations.
        Pass 'this' as third parameter so the lambda gets executed in the main thread (= where 'this' lives in)

        Qt has to stay free or it will die.

        J 1 Reply Last reply Reply Quote 5
        • J
          Jeff Barnes @Christian Ehrlicher last edited by

          @Christian-Ehrlicher Thanks

          1 Reply Last reply Reply Quote 1
          • KroMignon
            KroMignon @Jeff Barnes last edited by

            @Jeff-Barnes To solve the issue, you should use this as receiver of the signal, so the lambda will be executed in the right thread:

            QObject::connect(myObject, MyObject::mySignal, this, []() {
                  QMessageBox mb;
                  mb.setText("Hello world");
                  mb.exec();
              });
            

            It is an old maxim of mine that when you have excluded the impossible, whatever remains, however improbable, must be the truth. (Sherlock Holmes)

            1 Reply Last reply Reply Quote 0
            • First post
              Last post