设置 QML 上下文失败

Setting QML context fail

我正在尝试将 C++ class 连接到 QML,但我遇到了一个问题,编译时出现以下错误。

我正在添加一张图片来显示错误:

我正在使用一个简单的 class 来测试我的代码是否有效,这是代码 testing.h:

#ifndef TESTING_H
#define TESTING_H


class Testing
{
public:
    Testing();
    void trying();
};

#endif // TESTING_H

和testing.cpp:

#include "testing.h"
#include <iostream>
using namespace std;

Testing::Testing()
{

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

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

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

根据 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:

从上面可以看出class应该继承自QObject,另外如果要调用函数try必须在Q_INVOKABLE之前声明,这个我在以下代码:

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;
}

您还应该在 qml 文件中将 tryout() 更改为 trying()