Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-59331

It's not possible to connect two QML objects living in different threads

    XMLWordPrintable

Details

    Description

      This is an operation that is well supported from C++ side : the connection is automatically queued.

      Here this does not work :

      main.cpp :

      #include <QGuiApplication>
      #include <QQmlApplicationEngine>
      #include <QQmlContext>
      #include <QQmlComponent>
      #include <QDebug>
      #include <thread>
      
      int main(int argc, char *argv[])
      {
        QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
        QGuiApplication app(argc, argv);
      
        // Create a first engine in the main thread
        QQmlApplicationEngine engine;
        engine.load(QUrl(QLatin1String("qrc:/main.qml")));
      
        std::thread t{
          [&] {
            QEventLoop loop;
      
            // A second engine in another thread ; the main engine's root object is put as a context property.
            QQmlEngine engine2;
            engine2.globalObject().setProperty("hello", engine2.newQObject(engine.rootObjects().first()));
            QQmlComponent comp(&engine2, QUrl(QLatin1String("qrc:/dada.qml")));
      
            auto obj = comp.create();
            obj->setParent(&engine2);
            loop.exec();
          }
        };
      
        return app.exec();
      }
      

      main.qml :

      import QtQuick 2.7
      import QtQuick.Controls 2.0
      import QtQuick.Layouts 1.0
      
      ApplicationWindow {
          visible: true
          width: 640
          height: 480
          title: qsTr("Hello World")
      
          property real tutu
          Slider {
              onVisualPositionChanged: tutu = visualPosition
          }
      }
      

      dada.qml :

      import QtQuick 2.5
      import QtQml 2.2
      
      Item {
          id: self
          property real tata
      
          // The part that does not work : 
          Binding {
              target: self
              property: "tata"
              value: hello.tutu
          }
      }
      

      yields the error :

      QQmlEngine: Illegal attempt to connect to QQuickApplicationWindow_QML_2(0x19c0220) that is in a different thread than the QML engine QQmlEngine(0x7fc9e9818d00.

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            srutledg Shawn Rutledge
            jcelerier Jean-Michaƫl Celerier
            Votes:
            1 Vote for this issue
            Watchers:
            8 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Gerrit Reviews

                There are no open Gerrit changes