【问题标题】:QML Column doesn't set child object width automaticallyQML Column 不会自动设置子对象宽度
【发布时间】:2020-01-02 11:53:17
【问题描述】:

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

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 还是有更好的解决方法?

【问题讨论】:

  • “由于某种原因,我无法使用布局 qml 对象,因为它们锁定了我的目标系统。”我真的建议为此创建一个最小的示例(就像您对这个问题所做的那样)并发布一个关于它的问题。 :) 定位器有其用途,但布局非常有用。
  • 我尝试将一个空布局项添加到一个简单的“hello world”qml,即使这会导致崩溃。我试过了,相信我。我不知道目标系统出了什么问题,但它不在我的控制范围内。

标签: qt layout qml


【解决方案1】:

你说得对,QML Column 不会自动设置子对象的宽度,这是容器的预期行为(SwipeViewTabBar 等少数例外情况除外)。

因此,您有责任根据需要安排孩子的大小。

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

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

或使用锚点:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2011-11-06
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多