buttonqmlforeground

Foreground property for Button in QML


I am trying to change the foreground visibility of a QML button. Based on the content i read from internet and QML documentations, i have developed the below example.

import QtQuick 2.15
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3 
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")     
Button {
        id: myButton
        text: "Click Me"
        foreground: ColumnLayout{
            anchors.fill: parent
            visible: false
            Rectangle {
                id:rect1
                Text{
                    text: "Rect1"
                }
            }
            Rectangle{
                id:rect2
                Text{
                    text: "Rect2"
                }
            }
        }         
onClicked: {
            myButton.foreground.visible = !myButton.foreground.visible; // toggle visibility of foreground
        }
    }
}

When i am trying to exevute i am facing the following error.

"cannot assign to non-existent property foreground", the versions that i am importing are QtQuick 2.15 & QtQuick.Controls.2.15

Can someone help on achieving the above expectation.

Thanks in advance !!


Solution

  • You can give a try using contentItem as below

    import QtQuick 2.9
    import QtQuick.Window 2.2
    import QtQuick.Controls 2.2
    import QtQuick.Layouts 1.3
    
    Window {
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        Button {
            id: myButton
            text: "Click Me"
            implicitWidth: 162
            implicitHeight: 162
            contentItem:ColumnLayout{
                id: colLayout
                visible: false
                Rectangle{
                    width: 50
                    height: 50
                    color: "blue"
                    Text{
                        text:qsTr("Rect1")
                    }
                }
                Rectangle{
                    width: 50
                    height: 50
                    color: "blue"
                    Text{
                        text:qsTr("Rect2")
                    }
                }
            }
            onClicked: {
                colLayout.visible = !colLayout.visible; // toggle visibility of foreground
            }
        }
    }