Solved Custom QML Type from C++ with constructor with parameters. How?
-
Hello all!
Is there any way to create Custom QML Type with parameters in constructor? For now I found only solution to run function on Component.onCompleted. Something like this:CustomQmlType { ... Component.onCompleted: { init(Param1,Param2); } }
where function init implemented in C++:
public slots: void init(QVariant Param1,QVariant Param2);
Is there any way to set parameters at time of running constructor?
-
@bogong said in Custom QML Type from C++ with constructor with parameters. How?:
Is there any way to set parameters at time of running constructor?
No, there is no syntax for this. QML always instantiates using the default constructor.
What you can do, is to create the object dynamically via JS: there you can specify starting parameters (see https://doc.qt.io/qt-5/qml-qtqml-component.html#createObject-method). But it's the same as just setting some properties on the object in your example, so I doubt it helps you.
Other than that, there are some workarounds:
- introduce a singleton holding your params - then in constructor of your CustomQmlType, get parameter values from that singleton
- if you are OK with storing your QML type as a property of another type, you can always expose some C++ factory for your CustomQmlType objects, which will accept parameters
-
@sierdzio Thx a lot. Issue closed.
-
What can be usefull is to inherit from
QQmlParserStatus
and defer the logic of your component untillcomponentComplete
is called, you'll be sure all the property bindings have been evaluated.