Solved Signal fromm Cpp to QML
-
Dear All,
I'm looking to intercept a signal emited from a Cpp object in a QML object, I'm trying to achieve this setting my cpp file as a context Property :
main.cpp
#include "Source.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QQuickView viewer; Source source; viewer.rootContext()->setContextProperty("source", &source); viewer.setSource(QUrl(QStringLiteral("qrc:/main.qml"))); viewer.show(); return app.exec(); }
source hinerits from QObject :
source.h
#ifndef SOURCE_H #define SOURCE_H #include <QObject> class Source : public QObject { Q_OBJECT public: explicit Source(QObject *parent = 0); signals: void dataChanged(); }; #endif // SOURCE_H
Source.cpp :
#include "source.h" Source::Source(QObject *parent) : QObject(parent), N(256) { emit dataChanged(); }
and in my QML file I use Connections :
import QtQuick 2.7 Item { id: rootI width: 1000 height: 600 Connections: { target: source onDataChanged: { console.log("NewData") } } }
And on execution I get : "Invalid attached object assignment"
I have looked for the solutions in a lot of document but I still can't find what's wrong with that code....
-
Yup it works fine without the column.
thanks a lot and sorry for this oversight! -
Hello,
I don't know if this is the best way to do it, but this tutorial works perfectly :
https://andrew-jones.com/blog/qml2-to-c-and-back-again-with-signals-and-slots/ -
@Zhitoune I assume you are working close to this tutorial:
http://doc.qt.io/qt-5/qtqml-cppintegration-contextproperties.htmlBut what is the line number where the error occurs?
And what does N(256) do?
-
Thanks for our answers,
N(256) is just a remnant of the full code that I cleared for readability.
the error happens at the :Connections:{
line.
Yes I'm trying to emulate the solution based on the doc.qt without succes so far.
thanks Fheanor, I'll try this solution but I would like to understand why this method is not working.
-
This post is deleted! -
@Zhitoune Try to remove the colon behind Connections. It must be
Connections {not
Connections: { -
Yup it works fine without the column.
thanks a lot and sorry for this oversight!