2017-02-26 59 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 
     ... 
    } 
}