【问题标题】:Resize rectangle depending on whether text wraps or not QML根据文本是否换行 QML 调整矩形大小
【发布时间】:2018-01-07 14:32:50
【问题描述】:

所以我有一个矩形,里面有一个标签文本。如果文本太长而不能放在一行中,我想增加矩形的大小,否则应该保持不变。

到目前为止,我尝试使用 lineCount、clip、截断属性 qtdocs-

文本不合适,我得到省略号。但是,剪辑和截断总是返回 false。行数只返回当前行数,忽略它是否应该占用更多空间。

现在我正在尝试使用来自herecontentWidth。然而,这总是返回一个等于或小于实际宽度的值。我认为这应该返回它应该占据的总值?

我怎样才能做到这一点?

编辑

我正在尝试这样的事情,但无论我的文本有多长或截断程度如何,内容宽度总是小于标签的宽度。我从 qml 文档中得到的印象是 contentWidth 甚至会考虑省略的文本。

Rectangle{
  id: rec
  ...
  Label{
    id: messageText
    height: Format.singleLine
    text: "this text is very long and should be two lines"
    Component.onCompleted: {
      if (contentWidth > width){
        rec.height = Format.multipleLines
      }
    }
  }
}

第二次编辑

我了解到 lineCount 始终为 1 的原因是由于以编程方式创建对象(myRectangle 是包含标签的矩形):

    messages.source = Qt.resolvedUrl("myRectangle.qml");
    messages.item.message = message;

在创建标签的第一行之后,标签的 lineCount 为 1。然后我将尝试更改仅在此之后被截断的文本。

【问题讨论】:

  • 我只想做这样的事情:width: (contentWidth > width)? Format.multipleLines : Format.singleLine;

标签: qt qml qtquickcontrols2


【解决方案1】:

这样的事情怎么样:

height: lineCount > 1 ? Format.multipleLines : Format.singleLine

【讨论】:

  • 这不太奏效,因为 lineCount 会根据当前高度而有所不同。我最终将标签高度初始化为多行,然后如果只有一行,则将高度更改为 singleLine。
【解决方案2】:

如果您的 Rectangle 仅包含您的 Label,您可以依靠 Label 的 wrapMode 属性和 Rectangle 的 childrenRect.height 属性执行类似操作。

Rectangle {
    anchors.centerIn: parent
    width: 200
    height: childrenRect.height
    border.width: 1

    Label {
        id: messageText
        width: 200
        wrapMode: Text.Wrap
        text: "This text is very long very long. Like way too long to fit on a single line."
    }
}

或者,如果您不介意标签包含矩形,相反,您可以这样做:

Label {
    id: messageText
    anchors.centerIn: parent
    width: 200
    wrapMode: Text.Wrap
    text: "This text is very long very long. Like waaaaay too long to fit on a single line."

    Rectangle {
        anchors.fill: parent
        z: -1
        border.width: 1
    }
}

【讨论】:

    【解决方案3】:

    我不确定是否有更好的方法来做到这一点,但这段代码为我做了(这是在标签内):

       onContentWidthChanged: {
            if((lineCount === 1) && (contentWidth !== 0)){
                rec.height = Format.singleLine;
            }
            else{
                rec.height = Format.multipleLines;
            }
        }
    

    我将高度初始化为 Format.multipleLines。然后,一旦考虑到文本(ContentWidth 不为 0),我会检查 lineCount 是否为 1。如果是这样,我将高度修改为 format.singleLine。

    请注意,onContentWidth 在组件创建后会被调用两次。第一次 contentWidth 将始终为 0(因此需要检查它)。

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多