Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a 1 dimensional integer array from QML to C++?

So I have a signal:

QML:

signal qmlSendWorkflowIdsArraySignal(variant workflowIdsArray)

JS:

sendToCppWorkflowIdsArray(arrayOfWorkflowIds);

C++:

QObject::connect(qmlMainContentItemObject, SIGNAL(qmlSendWorkflowIdsArraySignal(QVariant)), &myController, SLOT(qmlToCppWorkflowIdsArraySlot(QVariant)));

C++ slot:

void qmlToCppWorkflowIdsArraySlot(QVariant workflowIdsArray)
{
  qDebug() << " +++++++++++++++ Cpp Array slot has been called: "<<workflowIdsArray;
}

Output:

+++++++++++++++ Cpp Array slot has been called:
QVariant(QVariantList, (QVariant(QString, "2") ,  QVariant(QString, "3") ,  QVariant(QString, "4") ) )
  • How do I read this QVariantList inside QVariant, ie, lets say I want to read this first element of the array, that is QVariant(QString, “2”), then the other and the other. This looks very complicated like this.
  • All I need is to pass an array of integers from QML to C++, so I can read this array. I dont want to use QVariant or a QVariantList, unless I have to as I see no other way to do it.

Does anyone have any suggestions?

like image 804
mshefiti Avatar asked Feb 11 '23 08:02

mshefiti


1 Answers

QML supports conversion between QList and Javascript values, for a limited amount of types. See the documentation on type conversion for details. No need to use QVariant for these.

With that, calling C++ methods from JS is easy:

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"]);

Note that I didn't use a signal here - in your case, the signal was connected from the C++ code, where the C++ code accessed an object from the QML layer. I try to avoid that, to force a cleaner separation between the C++ and QML layers, which makes it possible to completely change the QML code without needing to adapt the C++ layer. The C++ layer should never reach into the QML layer, the other way around is fine though.

like image 71
Thomas McGuire Avatar answered Feb 13 '23 21:02

Thomas McGuire