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

Switching visibility of a Rectangle via button



  • Hi all.
    I have a rectangle that I need to switch between visible / not visible via "myButton". So the button should change alternately the rectangle visibility. (with two states I think)...
    I've tried to make the button "checkable" in order to apply the condition below but doesn't work at all. What am I doing wrong?

    my main.qml:

    Button {
    	id: myButton
    	width: 80	
    	height: 20
            text: "click me"
    	checkable: true
    	onClicked: if (checked){
    		myRectangle.visible = true
    	}else{
    		myRectangle.visible = false
    	     }
    	}
    

    P.S.: Transparency is not ok for this case. So Opacity is not applicable as myRectangle content will keep active and I need to avoid any user interaction when the rectangle content is "invisible". that's why I need to make it not visible.

    Can you please help me? Thanks.



  • Try this;

    main.qml

    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtQuick.Controls 2.12
    
    Window {
        width: 200
        height: 200
        visible: true
        title: qsTr("Hello World")
    
        Rectangle {
            id: myRectangle
            width: 100
            height: width
            color: "red"
            anchors.centerIn: parent
        }
        Button {
            id: myButton
            width: 80
            height: 20
            text: "click me"
            checked: true
            onClicked: {
                if   (myRectangle.visible === false)
                      myRectangle.visible =  !false
                else  myRectangle.visible =   false
            }
            anchors {
                bottom: myRectangle.top
                bottomMargin: 10
                horizontalCenter: parent.horizontalCenter
            }
        }
    }
    

    Also, this may help too; https://stackoverflow.com/questions/46059068/setting-checked-property-of-a-button-in-qml



  • @ACaldas

        Rectangle {
            id: myRectangle
            visible: myButton.checked
            // other values
        }
        Button {
            id: myButton
            width: 80
            height: 20
            text: "click me"
            checkable: true
        }
    


  • Thanks gents,

    @eyllanesc is it possible to bind the myRectangle visibility to 2 buttons? Something like this:

    Rectangle {
       id: myRectangle
       visible:  myButton.checked : myButton2.checked
    

    no idea of the correct syntax...


Log in to reply