Search code examples
qmlqt5qtquick2qtquickcontrols2

How do I reset qml-properties to their default value?


I have a TextField where I want to conditionally show or hide the background. Here's a text field with a background:

TextField {
    id: with_background
}

and here's one without:

TextField {
    id: without_background
    background: null
}

I've tried setting the background conditionally to undefined, but that didn't work:

TextField {
    background: row.activeFocus ? TextField.background : null;
}

Is this even possible in QML?


Solution

  • TextField takes ownership of the background. When you set the background to null, the old background is destroyed to avoid backgrounds "piling up". Therefore you cannot toggle the background back and forth. However, if all you need is to toggle its visibility, you can do:

    TextField {
        background.visible: row.activeFocus
    }