2017-02-26 30 views
1

我是新的qml。 我開始用自定義項目開發一個小應用程序。 當我嘗試在應用程序anchor.top: first_item.bottom中使用定位自定義組件的矩形時,一個在另一個之下不起作用。Qt QML錨點不在定製項目

內容文件main.qml:

import QtQuick 2.5 

Item 
{ 
    id:main_screen 
    Rectangle 
    { 
     width: 300 
     height: 60 

     id: text_content 
     color: "DarkGray" 
     opacity: 0.9 
     border.color: "blue" 
     border.width: 3 
     radius: 5 
     z:6 

     Text { 
      id: titleText 
      width: parent.width 
      height: parent.height 
      font.pointSize: 20 
      font.family: "Arial" 
      horizontalAlignment: Text.AlignHCenter 
      verticalAlignment: Text.AlignVCenter 
      text: "Test - title" 
      color: "White"; style: Text.Raised; 
     } 
    } 


//..................This rectangle is shown below main_screen... so is OK 
    Custom_item 
    { 
     id:first_item 
     anchors.top: main_screen.bottom 
    } 

//..................This rectangle is not shown below first_item... but it shown on absolute top, in overlap of retangle title 
    Custom_item 
    { 
     id:second_item 
     anchors.top: first_item.bottom 
    } 

//..................This rectangle is not shown below second_item... but it shown on absolute top, in overlap of retangle title 
    Custom_item 
    { 
     id:third_item 
     anchors.top: second_item.bottom 
    } 
} 

內容文件Custom_item.qml

import QtQuick 2.5 

Item 
{ 
    id:testComponent 

    Rectangle 
    { 
     width: 300 
     height: 60 

     id: text_content 

     color: "DarkGray" 
     opacity: 0.9 
     border.color: "blue" 
     border.width: 3 
     radius: 5 
     z:6 
    } 
} 

我究竟做錯了什麼?

感謝

+1

我還建議發佈的截圖,而不是試圖解釋的用戶界面問題,即不是「這矩形不顯示在first_item下面,但它顯示在絕對頂部,與矩形標題重疊「一個屏幕快照將節省一千字:) – liorsolomon

+0

它具有一個mcve,它解釋了比千張圖片更多的問題。值得稱讚的第一篇文章! – derM

回答

2

問題在於你是錨定對象的尺寸範圍內。

雖然Rectangle■找一個widthheight,包封Item現在沒有,所以它基本上是在高度和寬度0像素,而Rectangle突出它。

如果你沒有任何理由把Rectangle放在Item之內,我建議你把Rectangle本身作爲文件的頂層元素。

原因具有Item也許是那些:

  • 隱藏Rectangles性能
  • 擁有的Item多的孩子,在邏輯上是兄弟姐妹的Rectangle
  • ...等原因可能存在; - )

儘管如此,您需要確保頂級項目始終正確的尺寸。所以你應該設置寬度和高度,在組件聲明中更好地使用implicitWidthimplicitHeight

例1:如果沒有Item

import QtQuick 2.5 
Rectangle { 
    id: root 
    width: 300 
    height: 60 

    color: "DarkGray" 
    opacity: 0.9 
    border.color: "blue" 
    border.width: 3 
    radius: 5 
    z:6 
} 

示例2:Item

import QtQuick 2.5 
Item { 
    id:testComponent 
    implicitHeight: 60 // < This 
    implicitWidth: 300 // < and that are important to have the dimensions 

    Rectangle { 
     id: text_content 

     anchors.fill: parent 
     color: "DarkGray" 
     opacity: 0.9 
     border.color: "blue" 
     border.width: 3 
     radius: 5 
     z:6 
    } 
} 
+0

非常感謝您澄清創意! – Nicola

0

您錨固所有Rectangle年代到Item因此你沒有得到想要的結果。簡單的變化頂部Rectangle當ID如下

Item 
{ 
    id: root   
    Rectangle 
    { 
     id:main_screen 
     ... 
    } 
}