首页 > 解决方案 > QML Column 不会自动设置子对象宽度

问题描述

我正在尝试使用列和行来布置我的用户界面。

import QtQuick 2.6
import QtQuick.Window 2.2

Window{
    height: 200
    width : 300

    Row{
        height: parent.height
        width: parent.width
        Column{
            width: parent.width / 2
            height: parent.height
            Text{
                text: "Hello World!"
            }
            Text{
                wrapMode: Text.WordWrap
                text: "This text is so long that it doesn't fit inside the column on a single line, but I'd assume that column sets child object width."
            }

            Rectangle{
                height: parent.height - y
                width: parent.width
                color: "#aa0000aa"
                Text{
                    anchors.bottom: parent.bottom
                    text: "Hello2"
                }
            }
        }
        Column{
            height: parent.height
            width: parent.width / 2
            Text{
                text: "Hello1"
            }

            Rectangle{
                height: parent.height - y
                color: "#4c00aa00"
                width: parent.width
                Text{
                    anchors.bottom: parent.bottom
                    text: "Hello2"
                }
            }
        }

    }
}

插图

可以看出,文本对象的宽度没有绑定到它的父对象。

由于某种原因,我无法使用布局 qml 对象,因为它们锁定了我的目标系统。

我只需要在我的代码中添加一些内容,width: parent.width还是有更好的方法来解决这个问题?

标签: qtlayoutqml

解决方案


你是对的,QML Column 不会自动设置子对象宽度,这是容器的预期行为(除了一些例外,如SwipeViewTabBar)。

因此,您有责任根据需要安排儿童尺寸。

在您的情况下,您必须明确设置的宽度Text才能应用包装:

Text {
    width: parent.width
    wrapMode: Text.WordWrap
    // ...
}

或使用锚:

Text {
    anchors {
        left: parent.left
        right: parent.right
    }
    wrapMode: Text.WordWrap
    // ...
}

推荐阅读