2017-07-01 59 views
0

我想連接一個C++類到QML,但我面臨一個問題,編譯時出現以下錯誤。設置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(); 
     } 
} 
+0

什麼是試用? – eyllanesc

+0

從發短信的方法,對不起,我沒有提到 –

+0

看到我的回答請 – eyllanesc

回答

1

按照documentation

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

從上面可以得出結論:類應該繼承自QObject,另外,如果你想調用的函數試圖您必須在申報之前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; 
} 

你也應該改變從tryout()在QML文件trying()