簡體   English   中英

設置QML上下文失敗

[英]Setting QML context fail

我正在嘗試將C ++類連接到QML,但是我遇到了一個問題,編譯時出現以下錯誤。

我正在添加圖像以顯示錯誤:

我正在使用一個簡單的類來測試我的代碼是否有效,這是代碼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();
       }
}

根據文檔

上下文屬性可以保存QVariant或QObject *值。 這意味着也可以使用這種方法注入自定義C ++對象,並且可以在QML中直接修改和讀取這些對象。 在這里,我們修改上面的示例以嵌入QObject實例而不是QDateTime值,並且QML代碼在對象實例上調用一個方法:

從上面可以得出結論,該類應繼承自QObject,此外,如果要調用該函數try,則必須在聲明中的Q_INVOKABLE之前,這在下面的代碼中顯示:

測試

#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()更改為tryout()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM