Home > OS >  Qt QML change item of a page dynamically
Qt QML change item of a page dynamically

Time:01-12

I have BasePage.qml like this:

Item {
    property alias content: loader.sourceComponent
    signal topBarLeftButtonClicked()

    TopBar {
    ...
    }

    Loader {
        id: loader
    }

    BottomBar {
    ...
    }
}

This way I can change dynamically the content of the page, but I must use Component, and I can't read properties of the content in a DerivedPage.
For example:

DerivedPage.qml

BasePage {
    onTopBarLeftIconClicked: item.text //error, item is not defined

    content: Component {
        TextField {
            id: item
        }
    }
}

Any solution?

CodePudding user response:

You can define an alias to the Loader's item property inside BasePage, like that:

property alias contentItem: loader.item

And refer to it instead of content item within DerivedPage.


Putting it all together:

// BasePage.qml
Item {
    property alias content: loader.sourceComponent
    property alias contentItem: loader.item
    signal topBarLeftButtonClicked()
    Loader { id: loader }
}

// DerivedPage.qml
BasePage {
    onTopBarLeftIconClicked: { contentItem.text = "clicked" }
    content: Component { TextField { } }
}

CodePudding user response:

I found a way to replace loader and components:

//BasePage.qml
Item {
    default property alias data: item.data
    signal topBarLeftButtonClicked()

    TopBar {
    ...
    }

    Item{
        id: item
    }

    BottomBar {
    ...
    }
}

//DerivedPage.qml
BasePage {
    onTopBarLeftIconClicked: textField.text = "string"

    TextField {
        anchors.fill: parent
        id: textField
    }
}

This way textField replace item in BasePage.qml

  •  Tags:  
  • Related