[SOLVED] How to create C++ object dynamically from within QML?
-
I use qmlRegisterType to register my C++ class to QML. If I use the C++ class as a property, it works well. But I can't find a way to create the C++ object dynamically (such as var a = new MyCppClass();)
Code piece,
@
MainForm {
//1, below line works but not what I want.
property CppNetHttp http: CppNetHttp{}
button1.onClicked: {
//2, below is what I want but it doesn't work. I get TypeError
// var http = new CppNetHttp();
http.get("http://bing.com/");
var text = http.getDownloadedData();
messageDialog.show(text);
}
}
@CppNetHttp is the C++ class.
So, how can I create C++ object similar as the code at comment 2?
Thanks
-
You can find the relevant information here http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html
-
[quote author="t3685" date="1420117578"]You can find the relevant information here http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html[/quote]
I read it. Seems it only works for QML types, rather than C++ object, no?
-
It should work, registered c++ classes are qml types.Have you tried it?
-
Even for registered C++ classes also it works. Please try. We have used this extensively in our solutions.
Here is the simple sample.
@ onClicked: {
var comp;
var obj;
comp = Qt.createComponent("DynamicCPP.qml")
obj = comp.createObject(top)
}@DynamicCpp.qml has object create of C++
DynamicCPP.qml has the following
@
import QtQuick 2.2
import QtQuick.Controls 1.1
import PthinkSUserClasses 1.0PthinkSUser{
id : twouser
Component.onCompleted: {
console.log("Created from QML dynamically ")
twouser.callme();
}
}@ -
Yeah that's exactly how I'm doing now. That way wraps the C++ type in a QML type, and then I create the QML type dynamically, like your sample code does.
My original question was different. I asked how to create and use the C++ type directly, without the QML type wrapper.
However, now I get used to and I really like the idea to wrap C++ type in a QML type, so my original question is not a problem any more.Thanks for your reply.
-
Just create an invokable C++ factory function to create and return the C++ object, and call it from QML.
-
You can't directly create object directly in QML like new MyClass. It needs to be treated like QML elements. You can try with other idea given by the previous post as well.
-
I think this is solved now so can you please append [SOLVED] to the title. Thank you.
9/9