2017-11-14 3 views
5

QML : I가 서명와 C++ 멤버 함수에 JS 객체 (지도)를 통과려고

Q_INVOKABLE virtual bool generate(QObject* context); 

a.generate({foo: "bar"}); 

방법을 사용하여 멤버 함수 ++ C에 JS 객체를 전달 가 호출됩니다 (중단 점을 통해 감지 됨). 그러나 전달 된 context 매개 변수는 NULL입니다. the documentation는 JS 객체가 QVariantMap로 전달 될 것이라고 언급 이후, 나는 서명

Q_INVOKABLE virtual bool generate(QVariantMap* context); 

를 사용하여 시도했지만이 MOC 동안 실패했습니다. 방법

Q_INVOKABLE virtual bool generate(QVariantMap& context); 

발생 사용 (에러 메시지 "& QVariantMap 알 수있어서 파라미터 유형"이다) QML 의해 런타임에서 발견되지한다.

설명서에는 QVariantMap을 C++에서 QML로 전달하는 예가 있지만 다른 방향으로는 전달하지 않습니다.

Q_INVOKABLE 대신 public slot을 사용하면 정확히 동일한 동작과 오류가 발생합니다.

답변

5

QML 세계에서 CPP 세계로 값을 전달하는 참조를 사용하지 마십시오. 이 간단한 예제는 작동 :

test.h

#ifndef TEST_H 
#define TEST_H 

#include <QObject> 
#include <QDebug> 
#include <QVariantMap> 

class Test : public QObject 
{ 
    Q_OBJECT 
public: 
    Test(){} 

    Q_INVOKABLE bool generate(QVariantMap context) 
    {qDebug() << context;} 
}; 

#endif // TEST_H 

MAIN.CPP

#include <QGuiApplication> 
#include <QQmlApplicationEngine> 
#include <QQmlContext> 
#include "test.h" 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); 
    QGuiApplication app(argc, argv); 

    QQmlApplicationEngine engine; 

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test()); 

    engine.load(QUrl(QLatin1String("qrc:/main.qml"))); 
    if (engine.rootObjects().isEmpty()) 
     return -1; 

    return app.exec(); 
} 

main.qml

import QtQuick 2.7 
import QtQuick.Controls 2.0 
import QtQuick.Layouts 1.3 

ApplicationWindow { 
    visible: true 
    width: 640 
    height: 480 
    title: qsTr("Hello World") 

    MouseArea 
    { 
     anchors.fill: parent 
     onClicked: 
     { 
      Test.generate({foo: "bar"}); 
     } 
    } 
} 

클릭하면 출력 콘솔에 msg가 다음과 같이 출력됩니다.

QMap(("foo", QVariant(QString, "bar"))) 
+0

감사합니다. – pmf

관련 문제