如何检测 textItem 的宽度并将另一个项目定位到右侧

How to detect the width of the textItem and position the another item to the right

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

例如:

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
        }
    } 

您不必明确设置 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

If the width or height is not explicitly set, reading these properties will return the parameters of the bounding rect of the text (if you have explicitly set width or height, you can still use paintedWidth and paintedHeight).