I am trying to connect a C++ class to QML but I am facing a problem, the following errors appear when compile.
I am adding an image to show the errors:
I am using a simple class just to test if my code works , here is the code testing.h:
#ifndef TESTING_H
#define TESTING_H
class Testing
{
public:
Testing();
void trying();
};
#endif // TESTING_H
and testing.cpp:
#include "testing.h"
#include <iostream>
using namespace std;
Testing::Testing()
{
}
void Testing::trying()
{
cout<<"hello"<<endl;
}
and main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "testing.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context= engine.rootContext();
Testing a;
context->setContextProperty("test",&a);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
and main.qml:
import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MouseArea{
anchors.fill: parent
onClicked: test.tryout();
}
}
According to the documentation:
From the above you can conclude that the class should inherit from QObject, in addition if you want to call the function try you must precede Q_INVOKABLE in the declaration, this I show in the following code:
testing.h
testing.cpp
You should also change from
tryout()
totrying()
in the qml file.