Threads and qml (error on signal)
-
Hi all -
I'm trying to create a worker thread that will emit a signal to be picked up in my QML. When I emit the signal I get an error:
QObject: Cannot create children for a parent that is in a different thread.
followed by a segmentation fault.
I've looked through the wiki, and it seems like I'm doing everything right. Here's the code, as brief as I can make it:
class Manager : public QObject { Q_OBJECT Q_PROPERTY(QByteArray replyData MEMBER m_replyData READ replyData WRITE setReplyData NOTIFY replyDataChanged) public: explicit Manager() {} QByteArray replyData() { return m_replyData; } signals: void replyDataChanged(QString newReply); private: QByteArray m_replyData; private slots: void setReplyData(QByteArray reply) { if (reply != m_replyData) { m_replyData = reply; emit replyDataChanged(m_replyData); // <== this causes the error. } } }; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); Manager manager; QThread thread(&app); QQmlApplicationEngine engine; int rc; engine.rootContext()->setContextProperty("manager", &manager); manager.moveToThread(&thread); QObject::connect(&thread, &QThread::finished, &manager, &QObject::deleteLater); thread.start(); rc = app.exec(); ... }
I'm including the QML related code on the off change that it might have something to do with this problem. Can anyone see what I might be doing wrong here?
Thanks...
-
@mzimmers said in Threads and qml (error on signal):
class Manager : public QObject { }; int main(int argc, char *argv[]) { engine.rootContext()->setContextProperty("manager", &manager); manager.moveToThread(&thread); ... }
I suspect the context property pointing to a QObject with affinity to another thread is the issue.
As @piervalli suggests, leave the Manager object in the UI thread, and give it a private worker QObject that performs the operations in another thread.
-
looking at this code i cant tell the exact issue, but that error you get whenever you call a function from one thread that attempts to create an object whose parent is in another thread.
An example would be if somewhere in your qml code it called a function of Manager that created an object with parent of Manager
As for the crash, it's probably because manager is not on the gui thread and QML really doesnt like communicating with anything not on the gui thread.
-
@mzimmers said in Threads and qml (error on signal):
class Manager : public QObject { }; int main(int argc, char *argv[]) { engine.rootContext()->setContextProperty("manager", &manager); manager.moveToThread(&thread); ... }
I suspect the context property pointing to a QObject with affinity to another thread is the issue.
As @piervalli suggests, leave the Manager object in the UI thread, and give it a private worker QObject that performs the operations in another thread.
-
-