所以我有一个信号:
QML:
signal qmlSendWorkflowIdsArraySignal(variant workflowIdsArray)
JS:
sendToCppWorkflowIdsArray(arrayOfWorkflowIds);
C ++:
QObject::connect(qmlMainContentItemObject, SIGNAL(qmlSendWorkflowIdsArraySignal(QVariant)), &myController, SLOT(qmlToCppWorkflowIdsArraySlot(QVariant)));
C ++插槽:
void qmlToCppWorkflowIdsArraySlot(QVariant workflowIdsArray)
{
qDebug() << " +++++++++++++++ Cpp Array slot has been called: "<<workflowIdsArray;
}
输出:
+++++++++++++++ Cpp Array slot has been called:
QVariant(QVariantList, (QVariant(QString, "2") , QVariant(QString, "3") , QVariant(QString, "4") ) )
有人有任何建议吗?
答案 0 :(得分:3)
QML支持QList和Javascript值之间的转换,适用于有限数量的类型。有关详细信息,请参阅documentation on type conversion。无需使用QVariant。
有了这个,从JS调用C ++方法很简单:
tester.h:
class Tester : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE void bla(const QList<QString> &strings) {
qDebug() << "Tester::bla():" << strings;
}
};
main.cpp中:
Tester tester;
viewer.engine()->rootContext()->setContextProperty("_tester", &tester);
QML:
onClicked: _tester.bla(["asdf", "foo", "bar"]);
请注意,我在这里没有使用信号 - 在您的情况下,信号是从C ++代码连接的,其中C ++代码从QML层访问对象。我试图避免这种情况,强制在C ++和QML层之间进行更清晰的分离,这样就可以完全改变QML代码而无需调整C ++层。 C ++层永远不应该进入QML层,反之亦然。
答案 1 :(得分:3)
将数组从QML传递到C ++的一种方法如下:
创建一个将接收整数数组的类:
<强> DataReceiver.h 强>
#include <QQuickItem>
#include <QList>
class Receiver : public QQuickItem
{
private:
Q_OBJECT
Q_PROPERTY (QList<int> xx READ xx WRITE setXX NOTIFY xxChanged)
QList<int> m_xx;
public:
Receiver (QQuickItem *parent = 0) {}
QList<int> xx() const
{
return m_xx;
}
public slots:
void setXX (QList<int> arg)
{
if (m_xx != arg) {
m_xx = arg;
emit xxChanged (arg);
}
}
signals:
void xxChanged (QList<int> arg);
};
在main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "DataReceiver.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
const char* ui = "HELLO"; // @uri HELLO
qmlRegisterType <Receiver> (ui, 1, 0, "DataReceiver");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
return app.exec();
}
在QML(main.qml)
import QtQuick 2.2
import QtQuick.Window 2.1
import HELLO 1.0
Window
{
visible: true
width: 360
height: 360
id: head
property variant myArray: [1,2,3]
DataReceiver
{
id: dataReceiver
xx: head.myArray
}
}
您可能还想检查一下:
How to push values to QML property variant two dimensional array - dynamically?