如何从QML向C ++发送一维整数数组?

时间:2014-12-15 17:24:48

标签: javascript c++ arrays qt qml

所以我有一个信号:

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") ) )
  • 如何在QVariant中读取此QVariantList,即,我想说 读取数组的第一个元素,即QVariant(QString, “2”),然后是另一个和另一个。这看起来非常复杂 这个。
  • 我需要的是将一个整数数组从QML传递给C ++,所以我 可以读取这个数组。我不想使用QVariant或QVariantList,除非我必须这样做,因为我没有其他方法可以做到这一点。

有人有任何建议吗?

2 个答案:

答案 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?