Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML - Passing Javascript associative array to C++

In my app I have a class which registered as singleton for QML. My purpose is collecting values in QML as associative array and passing this array to C++. This is the simplified version of the class:

class Config : public QObject
{
Q_OBJECT
private:
  Config(QObject *parent = 0);
public:
  static Config *instance();
  ~Config();
  Q_INVOKABLE void sendValue (const QVariantMap &map) {
    qWarning() << map.size();
  }
}

and here I register an instance of the class as singleton:

qmlRegisterSingletonType<Config>("myNS", 1, 0, "Config", config_singletontype_provider);

In some place in QML file I try to pass javascript array back to c++;

function sendValue() {
  var arr = [];
  arr["key"] = "value";
  Config.sendValue(arr);      
}

But nothing passed. The map.size() in C++ returns 0. May be I need some additional conversion?

like image 667
folibis Avatar asked Jun 23 '14 22:06

folibis


People also ask

What is associative array in JavaScript?

Associative array uses string instead of a number as an index. Here, we need to understand that Javascript does not support Associative array, but as all arrays in javascript are objects and javascript’s object syntax helps in imitating an Associative array.

How do I transfer data from QML to C++ or JavaScript?

The QML engine has built-in support for converting a number of Qt types to related JavaScript types, and vice-versa, when transferring data between QML and C++. This makes it possible to use these types and receive them in C++ or JavaScript without needing to implement custom types that provide access to the data values and their attributes.

How do I get data from QML to listview?

QML / Javascript Array The simplest method is using a Javascript array to feed primitive type-based data into a ListView. All QML delegates inside a model view contain a model property that represents the data for that particular index in the data model array.

How do you get data from a QML model?

All QML delegates inside a model view contain a model property that represents the data for that particular index in the data model array. In this example, the data model is a JS array – therefore, the data is available directly through the modelData property of the model object.


1 Answers

Ok, I answer to my own question ) The documentation is not so clear but, as I understand, Qt converts JS array to QVariantList and JS object to QVariantMap So in my case I just need to create an object, not array:

var arr = {};
like image 85
folibis Avatar answered Oct 01 '22 20:10

folibis