Qt QML 锚点在自定义项目中不起作用

Qt QML anchor not working in custom Item

我是 qml 新手。 我开始开发一个带有自定义项目的小应用程序。 当我尝试在应用程序 anchor.top: first_item.bottom 中使用来定位自定义组件的矩形时,一个在另一个下方不起作用。

内容文件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
    }
}

我做错了什么?

谢谢

您正在将所有 Rectangle 锚定到 Item,因此您没有得到想要的结果。简单改变topRectangle的id如下

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

问题出在您锚定的 objects 的尺寸范围内。

虽然 Rectangle 有一个 width 和一个 height,但封闭的 Item 有 none,所以它的高度基本上是 0 像素和宽度,而 Rectangle 突出它。

如果您没有任何理由将 Rectangle 包含在 Item 中,我建议您将 Rectangle 本身作为文件。

拥有 Item 的原因可能是:

  • 隐藏 Rectangles 属性
  • Item 有多个 children,它们在逻辑上是 Rectangle
  • 的兄弟姐妹
  • ...可能存在其他原因 ;-)

不过,您需要确保顶级项目始终具有正确的尺寸。所以你应该设置宽度和高度,最好在组件声明中设置 implicitWidth and implicitHeight

示例 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
    }
}