【问题标题】:How to detect the width of the textItem and position the another item to the right如何检测 textItem 的宽度并将另一个项目放置在右侧
【发布时间】:2018-04-25 18:29:47
【问题描述】:

我有一个 QML TextItem,其中的文本是动态设置的。我无法确定文本的宽度,因为文本可以包含任意数量的字符。 我需要在它旁边放置另一个文本项。 那么当我们无法确定文本的宽度时如何锚定到文本项的右侧,因为文本可以随时增长。不允许使用 Wrap 或 Elide

例如:

Text
    {
        id: distance
        width: //dont know what to provide

        font.bold: true

        verticalAlignment:Text.AlignBottom
        horizontalAlignment:Text.AlignLeft
        maximumLineCount: 1

        onTextChanged:
        {
            console.log("$$$$$___Text is been changed:" + txt_distance.paintedWidth +" "+ paintedHeight)

        }

        anchors
        {
            bottom: parent.bottom
            bottomMargin: 2
            left: parent.left
            leftMargin: 20
            right: //Dont know what to give

        }

和邻居项目

Text
    {
        id: address

        font.bold: true

        verticalAlignment:Text.AlignBottom
        horizontalAlignment:Text.AlignLeft
        maximumLineCount: 1

        anchors
        {
            bottom: parent.bottom
            bottomMargin: 2
            left: distance.right <-- Please help 
            right: parent.right
            rightMargin: 20
        }
    } 

【问题讨论】:

    标签: qt qml qtextedit


    【解决方案1】:

    您不必显式设置width,因为它将设置为paintedWidth

    你的例子可以这样简化:

    Text {
        id: distance
        text: "Hello"
    }
    
    Text {
        text: "Wagmare"
        anchors.left: distance.right
    }
    

    更好的解决方案是使用Row

    Row {
        Text {
            text: "Hello"
        }
    
        Text {
            text: "Wagmare"
        }
    }
    

    Use Case - Displaying Text In QML

    如果没有明确设置宽度或高度,则读取这些属性 将返回文本边界矩形的参数(如果你 已经明确设置了宽度或高度,您仍然可以使用paintedWidth 和paintedHeight)。

    【讨论】:

    • 谢谢 augre 。如果文本是在运行时设置的怎么办? .就像在接收数据后的 .cpp 中一样,我将更新文本属性。它会工作吗?
    • 是的,如果你不手动设置宽度,如果文本发生变化,它仍然会绑定到paintedWidth。你可以用计时器试试:Timer { id: timer onTriggered: distance.text = "Hi" } Component.onCompleted: timer.start()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多