Embedding C++ Objects into QML with Context Properties
I reused your qml file to start a fresh project in QtCreator.
Please find below the files I used to compile and use the application successfully:
the project file: test.pro
# The .cpp file which was generated for your project. Feel free to hack it.
SOURCES += main.cpp
# Please do not modify the following two lines. Required for deployment.
include(qtquick2applicationviewer/qtquick2applicationviewer.pri)
qtcAddDeployment()
HEADERS += myclass.h
myclass.h:
#include <QObject>
#include <qdebug.h>
class MyClass : public QObject
{
Q_OBJECT
public slots:
void doStuffFromQmlSlot()
{
qDebug() << Q_FUNC_INFO;
}
public:
MyClass()
{
qDebug() << Q_FUNC_INFO;
}
};
main.cpp:
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include "myclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MyClass myClass;
QtQuick2ApplicationViewer viewer;
viewer.rootContext()->setContextProperty("myclass", &myClass);
viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer.showExpanded();
return app.exec();
}
and qml/main.qml being exactly the snippet provided in your question
if you start the project using QtCreator you'll also have the qtquick2applicationviewer/ folder ready to be used.
Then qmake && make && ./test
will launch the application.
If you click on the text element you'll get:
MyClass::MyClass()
void MyClass::doStuffFromQmlSlot()