Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Assigning custom property in dynamically created QML component. How?



  • Hello all!
    I am creating component dynamically from URL and don't able to assign custom property of component.
    CustomComponent.qml

    Rectangle {
    
    	property string pTestText: "Default value";
    		
    	id: idRoot;
    			
    	Text {
    			
    		id: idText;
    		text: idRoot.pTestText;
    	}
    }
    

    Creating component dynamically and the pTestText property do not working, it's getting default value:

    var CustomComponent = Qt.createComponent("qrc:/CustomComponent.qml");
    CustomComponent.pTestText = "Test Text";
    

    When I am doing it directly in QML - everything works fine:

    ...
    CustomComponent {
    	pTestText: "New Value";
    }
    ...
    

    The question is how to define it from JS? Am I missing something?



  • You should set properties to an objects created by this component.

    let component = Qt.createComponent("qrc:/CustomComponent.qml");
    let obj = component.createObject(parent, {/* properties */pTestText: "42"});
    // Properties can be set later
    obj.pTestText = "hello";
    


  • @IntruderExcluder But what if I need to push it into StackView? What should be in exchange of parent? My use-case is creating dynamically QML component define parameters and push it into StackView. Will it be destroyed when I pop it out?



  • You can set parent as null, but you must take care of lifetime of such objects. The parent property is like same as it works with QObject instances: remove all childs on destroy.



  • Found solution. This works for me in StackView:

    var CustomComponent = Qt.createQmlObject('
    	import QtQuick 2.0;
    	CustomComponent {}
    ', oStackView, 'oCustomComponent');
    CustomComponent.pTestText = "Value at time of creating";
    oStackView.push(CustomComponent);
    

    Issue closed.



  • So what's the difference between your example and using push method of StackView?


  • Moderators

    @IntruderExcluder probably using the correct property name pTestText instead of the undefined pText


  • Qt Champions 2018

    @bogong said in Assigning custom property in dynamically created QML component. How?:

    Found solution. This works for me in StackView:

    var CustomComponent = Qt.createQmlObject('
    	import QtQuick 2.0;
    	CustomComponent {}
    ', oStackView, 'oCustomComponent');
    CustomComponent.pTestText = "Value at time of creating";
    oStackView.push(CustomComponent);
    

    Issue closed.

    Or simpler (way simpler) :

    oStackView.push("CustomComponent.qml", { pTestText: "Value at time of creating" } );
    


  • This post is deleted!

Log in to reply