2016-12-27 75 views
0

我想了解錨點如何在QML(Qt Quick 2.0)中工作。我有一個簡單的項目是這樣的:QML在設置錨點時忽略寬度和高度

AddButton.qml:

Item { 

    Button { 
     text: "ADD" 
     width: 100 
     height: 50 
    } 

} 

其中我添加到主QML文件中像這樣:

main.qml:

Item { 
    id: root 
    width: 800 
    height: 600 

    AddButton { 
     id: addButton 
    } 

} 

這工作正常。然而,當我試圖把按鈕在右下角使用的角落錨,該按鈕就會消失:

main.qml:

Item { 

    ..... 

    AddButton { 
     id: addButton 
     anchors.right: parent.right 
     anchors.bottom: parent.bottom 
    } 

} 

它只回來,如果我設置的寬度和高度在主QML文件級別:

main.qml:

Item { 

    ..... 

    AddButton { 
     id: addButton 
     width: 100 
     height: 50 
     anchors.right: parent.right 
     anchors.bottom: parent.bottom 
    } 

} 

小號o我想知道,爲什麼當我設置錨時按鈕會消失?有沒有什麼辦法可以讓它在沒有設置主QML文件中的寬度和高度的情況下工作(基本上是爲了讓它使用AddButton.qml中設置的任何大小?)

回答

3

問題是封裝Item還沒有明確的widthheight。在這種情況下,發動機指的是「自然」機能/高度,即屬性。在大多數情況下,即使在這種特定情況下,這些屬性也幾乎爲零。因此,您的自定義類型具有零維度。 因此AddButton.anchors.bottom其實在封裝Button的最頂端,這又突出了封裝Item

有兩件事情這一點:

你不需要用項目來封裝Button除非你想隱藏Button的內部。

如果後者是你的願望,試試這個:

Item { 
    width: 100 //give the object a dimension! 
    height: 50 

    Button { 
     text: "ADD" 
     anchors.fill: parent 
    } 
} 

現在你可以錨定它,它也不會在其他地方positionated。

+1

隱式屬性總是被忽視,但它們非常重要,因此應考慮向新手討論它們。 – BaCaRoZzo

+0

你是對的!感謝您的編輯;-) – derM