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

Restricting dynamic creation of QML component to one instance



  • Hi,
    This is regarding dynamic creation of QML component/object. Here is my code, which is taking care of creating component and object.

        property var component: null
        property var obj: null
    
        function takeAction()
        {
            console.log("takeAction called")
            component = Qt.createComponent("FileSelector.qml")
            if (component.status !== Component.Ready)
            {
                component.statusChanged.connect(finishCreation)
            }
            else {
                finishCreation()
            }
    
        }
    
        function finishCreation()
        {
            console.log("Finish creation called")
            if (component.status === Component.Ready)
            {
                obj = component.createObject(aipage, {x: 100, y: 100, fsTheme: theme})
                if (obj === null)
                {
                    console.log("Object creation failed")
                }
            }
            else if (component.status === Component.Error)
                console.log("Component creation error : " + component.errorString())
        }
    

    I am calling the takeAction method on press of a button. And it is working fine. In FileSelector.qml, I have a Done button, on press of which, I am calling destroy method for FileSelector.qml.
    The problem is every time, I am pressing the button, a component and object is getting created. Is there anyway to restrict the same to one active component and object?
    I tried with a null check for component. But I am not able to see it getting null at anytime.

    I figured out a solution:
    I am checking null for component creation. If component is not null just avoiding the creation. On destroy of my FileSelector object, I am emitting a signal fileSelectorDestroyed. Depending on the signal, I am assigning null to my local component and object

    Please let me know, if there is any better way of doing the same.



  • Its too bad there isn't the equivalent of QPointer for QML objects. Then you could fill the pointer on creation and it would get set back to null on destruction. Perhaps that can be done in the onDestroyed event for the object.


Log in to reply