Create QML or JavaScript Object in C++
-
Hi,
As I see in "Interacting with QML Objects from C++":http://qt-project.org/doc/qt-5/qtqml-cppintegration-interactqmlfromcpp.html, the way to Create QML Object in C++ is like this:@ // Using QQmlComponent
QQmlEngine engine;
QQmlComponent component(&engine,
QUrl::fromLocalFile("MyItem.qml"));
QObject *object = component.create();
...
delete object;@This is a static way as we must write a qml file in advance, how to create an qml object dynamically?
Maybe something like this: create("Rect")?If so, we can register a C++ class, MyClass for example, to QML engine and use it in C++ like this create("MyClass"), right?
Is there any way to create JavaScript object in C++ directly?
-
You can use setData to create QML text dynamically.
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: "Hello world!" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());It should be possible to create the object in C++. When the myclass is C++ class itself, why do you want to register in QML and then create object in C++. You can as well create in C++ itself. May be I'm missing something here ?
-
[quote author="Dheerendra" date="1406270840"]You can use setData to create QML text dynamically.
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData("import QtQuick 2.0\nText { text: "Hello world!" }", QUrl());
QQuickItem *item = qobject_cast<QQuickItem *>(component.create());It should be possible to create the object in C++. When the myclass is C++ class itself, why do you want to register in QML and then create object in C++. You can as well create in C++ itself. May be I'm missing something here ?[/quote]
Thanks for your reply, and your answer does help.In this way, component can eval the data, and create an object dynamically.Register c++ class into qml and then create qml object in c++ is just question, not for use.I will test that. Thanks again.
And another question:
Is that the only way to create qml object in c++,Is there any way to create JavaScript object in C++ directly without QML, do you have any idea? -
If you want QML object, that is the only way. If are not worried about QML, you can check QScriptable module for JavaScript and C++ integration.
-
[quote author="Dheerendra" date="1406300961"]If you want QML object, that is the only way. If are not worried about QML, you can check QScriptable module for JavaScript and C++ integration. [/quote]
Ok,I will try it.Thanks a lot~