Rectangle width is '0' if i try to access in "Component.OnCompleted"



  • Hello all i want to get the width of a rectangle in "Component.OnCompleted" .Following is my code:

    main.qml

    import QtQuick 2.6
    import QtQuick.Controls 2.2
    import QtQuick.Window 2.3
    
    ApplicationWindow {
        id: appWindow
        visible: true
        width: 600
        height: 400
        title: qsTr("test")
        flags:  Qt.Window | Qt.FramelessWindowHint
        
        MyRect{
            id:rect
        }
    }
    

    MyRect.qml

    import QtQuick 2.6
    import QtQuick.Controls 2.2
    
    Rectangle{
            id:rectParent
            anchors.fill:parent
            Rectangle{
                id:rectChild
                width:parent.width * 0.75
                height: parent.height * 0.70
                Component.onCompleted: {
                    console.log("Width=",width) //prints "0" .
                    //code to create component follows  and i need the width.
                }
            }
        }
    

    What is the approach that i should use to create a component on completion? i can't use timers.



  • @pra7 Have you tried moving the code to rectParent's Component.onCompleted?



  • Hi,
    There is an concatenation error in 'MyRect.qml' :

    Component.onCompleted: {
             
                             console.log("Width=",width) //prints "0" .  //  <<< Error here
               
            }
    

    Should be :

    Component.onCompleted: {

                             console.log("Width=" + width) //prints "0" .  //  '+'  and not   ' , '               
            }
    

    LA



  • @LeLev That doesn't make any difference



  • @Eeli-K Even there it's the same .. I am getting width has '0'



  • Oh sorry, i just tested console.log("Width=",width) and it works. My bad.



  • Replace 'parent' by parents id

    /** MyRec.qml **/
    import QtQuick 2.6

    Rectangle{
    id:rectParent

        color: "grey"
        property alias _recChildW : rectChild
    
    Rectangle{
            id:rectChild
            width:rectParent.width * 0.75  // parent id
            height: rectParent.height * 0.70 //   parent id
    
        }
    
    
    }
    

    /Main/
    import QtQuick 2.7
    import QtQuick.Controls 2.0
    import QtQuick.Layouts 1.3

    ApplicationWindow {
    id:root
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

        MyRec{
                  id: customRec
                height:root.height // here : parent id
                width:root.width   // here  : parent id
    
                Component.onCompleted:  console.log("width " + _recChildW.width) 
    
            }
    

    }



  • @LeLev Thanks , I will try the same .


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.