我正在尝试将 JS 对象(映射)传递给带有签名的 C++ 成员函数
Q_INVOKABLE virtual bool generate(QObject* context);
通过使用
a.generate({foo: "bar"});
调用了方法(通过断点检测),但传递的context
参数为NULL
。自 the documentation提到 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 世界。 这个简单的例子有效:
测试.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"});
}
}
}
在窗口中单击,这将在输出控制台中打印以下消息:
QMap(("foo", QVariant(QString, "bar")))
关于javascript - QML:将 JS 对象传递给 C++ 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47287213/