RowLayout忽略Layout.minimumWidth

时间:2015-11-24 20:47:57

标签: qml qt5 qtquick2

当窗口太小时,texttext2应该被恰当地省略(当空间不足以覆盖整个字符串时显示三个点)。 Layout.preferredWidth设置为text.implicitWidth并添加了一些填充,但我甚至设置了Layout.minimumWidth,因此当空间不足时,文本可以被省略。似乎RowLayout忽略了Layout.minimumWidth并保留了Layout.preferredWidth,因此文字仍然是width Layout.preferredWidth并且永远不会被删除。怎么了?

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    contentItem.minimumWidth: 50

    RowLayout {
        id: ntoolbarline

        anchors.fill: parent

        Rectangle {
            color: "red"

            Layout.preferredWidth: text.implicitWidth + 40
            Layout.preferredHeight: 25
            Layout.minimumWidth: 25
            Layout.minimumHeight: 25
            Layout.maximumWidth: text.implicitWidth + 40

            Text {
                id: text
                anchors.centerIn: parent
                text: "Foooooooo"
                elide: Text.ElideRight
                width: parent.width - 40
                renderType: Text.NativeRendering
            }
        }

        Rectangle {
            color: "red"

            Layout.preferredWidth: text2.implicitWidth + 40
            Layout.preferredHeight: 25
            Layout.minimumWidth: 25
            Layout.minimumHeight: 25
            Layout.maximumWidth: text2.implicitWidth + 40

            onWidthChanged: console.log("layout item width: " + width) // only one output when app started

            Text {
                id: text2
                anchors.centerIn: parent
                text: "Baaaaaaaar"
                elide: Text.ElideRight
                width: parent.width - 40
                renderType: Text.NativeRendering
            }
        }

        Item {
            id: spacer
            Layout.fillWidth: true
            onWidthChanged: console.log("spacer width: " + width) // outputs whenever the window is resized
        }

    }

}

1 个答案:

答案 0 :(得分:2)

这里有两个主要问题:

  1. fillWidth未定义
  2. Text centerIn是父Rectangle
  3. 没有1. Rectangle s不能在期望的约束内增长或缩小。通过使用2. Text元素,因为它的大小和边界没有特定的约束,因此Text无法正确检查是否需要elide。正确的方法是使用fill并通过verticalAlignment的{​​{1}}和horizontalAlignment设置路线。

    最终重访的代码如下所示:

    Text