2017-07-01 21 views
0

QMLに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(); 
     } 
} 
+0

トライアウトとは? – eyllanesc

+0

テクスチャからの方法、申し訳ありませんが、私は言及していませんでした –

+0

私の答えを参照してください – eyllanesc

答えて

1

documentationによれば:

コンテキスト特性はQVariantまたはQObjectを*値のいずれかを保持することができます。この は、カスタムC++オブジェクトもこの方法を使用して注入でき、 これらのオブジェクトはQMLで直接変更して読み取ることができます。ここでは、QObjectのインスタンスの代わりに、 QDateTime値を埋め込むために、上記の例を修正し 、およびQMLのコードは、オブジェクト インスタンスのメソッドを呼び出します。

からは、クラスが継承するべきであると結論付けることができ、上記

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 
:関数を呼び出すしたい場合はQObjectから、加えてあなたは、宣言の中で、私は次のコードで表示し、これをQ_INVOKABLEに先行しなければならないしてみてください

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()に変更する必要があります。

関連する問題