willpnw
willpnw

Reputation: 775

How to expose global strings and ints to C++, QML, and JS

Our team is developing a Qt application which makes use of C++, QML, and JS. What is the best way to expose non-language specific strings, representing filenames and ints representing error codes, so that all languages can easily use them?

Upvotes: 0

Views: 214

Answers (1)

dtech
dtech

Reputation: 49319

The most efficient and clean solution would be to implement those strings and ints as properties of a QObject, then create an instance of that object in main.cpp and register it as a singleton.

// before main()
YourType data;
static QObject * getData(QQmlEngine * e, QJSEngine *) {
  e->setObjectOwnership(&data, QQmlEngine::CppOwnership); // just in case
  return &data;
}


// in main()
qmlRegisterSingletonType<YourType>("Core", 1, 0, "Data", getData);
QQmlApplicationEngine engine;
//...

And now you have a global data for C++, and a global Data for QML. In the first case you will need to declare data as an extern in sources which need to access it, in the second case you will need to import Core 1.0 in order to access Data and its properties.

Upvotes: 1

Related Questions