[英]QML: passing JS object to C++ member function
我正在嘗試將JS對象(映射)傳遞給具有簽名的C ++成員函數
Q_INVOKABLE virtual bool generate(QObject* context);
通過使用
a.generate({foo: "bar"});
該方法被調用(通過斷點檢測),但是傳遞的context
參數為NULL
。 由於文檔中提到JS對象將作為QVariantMap
傳遞,因此我嘗試使用簽名
Q_INVOKABLE virtual bool generate(QVariantMap* context);
但這在MOC期間失敗了。 使用
Q_INVOKABLE virtual bool generate(QVariantMap& context);
導致無法在運行時通過QML找到該方法(錯誤消息為“未知方法參數類型:QVariantMap&”)。
該文檔僅提供了將QVariantMap
從C ++傳遞到QML的示例,而沒有其他方向。
使用public slot
而不是Q_INVOKABLE
顯示完全相同的行為和錯誤。
不要使用引用將值從QML世界傳遞到CPP世界。 這個簡單的例子起作用:
測試
#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"});
}
}
}
單擊窗口,這將在輸出控制台中顯示以下消息:
QMap(("foo", QVariant(QString, "bar")))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.