首页 > 解决方案 > QtQuick:用Elide调整两个文本字段的大小

问题描述

我连续有两个标签 A 和 B,它们需要固定在一起,这样它们之间就没有间距。A 不允许大于它的内容,因为 B 就像一个细节标签。看到会很奇怪Google Chrome_____(the current browser)Google Chrome (the current browser)____在这种情况下你会想要的。两者都有一个共同的父母,他们可以填补。内容方面,A 和 B 都可以是两者中较大的一个。整个事情应该左对齐,这样 A 锚定到父级的左侧,B.left == A.right。

当没有足够的空间时,两个项目都应该缩小并消失,直到它们适合父项,例如Google Chr..(The current br...

最后一部分是我不知道该怎么做。

我使用 2 个标签而不是 1 个标签,因为它们需要自己的省略和自己的样式。我目前的解决方案将简单地省略 B,而不是缩小 A。

RowLayout
        {
            spacing: 0
            anchors.left: parent.left
            anchors.right: customisedSettings.left
            anchors.leftMargin: UM.Theme.getSize("default_margin").width

            Label
            {
                id: textLabelA
                text: qualityName()
                font: UM.Theme.getFont("default")
                color: UM.Theme.getColor("text")
                Layout.margins: 0
                height: contentHeight
                verticalAlignment: Text.AlignVCenter
                renderType: Text.NativeRendering
                elide: Text.ElideRight

                function qualityName() {
                    [...]
                }
            }

            Label
            {
                id: textLabelDetail
                text: activeQualityDetailText()
                font: UM.Theme.getFont("default")
                color: UM.Theme.getColor("text_detail")
                anchors.verticalCenter: textLabelA.verticalCenter
                Layout.margins: 0
                Layout.fillWidth: true

                height: contentHeight
                verticalAlignment: Text.AlignVCenter
                renderType: Text.NativeRendering
                elide: Text.ElideRight

                function activeQualityDetailText()
                {
                    [..]
                }
            }
        }

标签: qtqmlqtquick2

解决方案


您可以通过将它们放入 aRowLayout并设置它们来做到这一点Layout.fillWidth: true,以便它们都缩小。为确保第一个 Label 不大于所需,请设置Layout.maximumWidth: implicitWidth.

这给了我们:

import QtQuick 2.8
import QtQuick.Controls 2.1
import QtQuick.Window 2.3
import QtQuick.Layouts 1.2

Window {
    visible: true
    width: 600
    height: 400

    RowLayout {
        anchors.fill: parent
        Label {
            text: "Google Chrome"

            Layout.fillWidth: true
            Layout.maximumWidth: implicitWidth

            elide: Text.ElideRight
        }
        Label {
            text: "(the current browser)"
            color: "darkgray"

            Layout.fillWidth: true

            elide: Text.ElideRight
        }
    }
}

推荐阅读