Setting QML context fail

184 views Asked by At

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();
       }
}
1

There are 1 answers

0
eyllanesc On BEST ANSWER

According to the documentation:

Context properties can hold either QVariant or QObject* values. This means custom C++ objects can also be injected using this approach, and these objects can be modified and read directly in QML. Here, we modify the above example to embed a QObject instance instead of a QDateTime value, and the QML code invokes a method on the object instance:

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

#ifndef TESTING_H
#define TESTING_H

#include <QObject>

class Testing: public QObject
{
    Q_OBJECT
public:
    Testing(QObject *parent=0);
    Q_INVOKABLE void trying();
};

#endif // TESTING_H

testing.cpp

#include "testing.h"

#include <iostream>
using namespace std;

Testing::Testing(QObject *parent):QObject(parent)
{

}

void Testing::trying()
{
    cout<<"test"<<endl;
}

You should also change from tryout() to trying() in the qml file.