Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Measuring width of rich text with TextMetrics



  • When text contains line break, TextMetrics width returns width as if there is no line break in text. FontMetrics behaves the same.

    import QtQuick 2.11
    import QtQuick.Window 2.11
    
    Window {
        id: mainWindow
        visible: true
        width: 640
        height: 480
        title: qsTr("Hello World")
    
        TextMetrics {
            id: textMetrics
            font.family: "Arial"
            elide: Text.ElideMiddle
            elideWidth: 100
            font.pointSize: 14
            text: "Hello<br>World!!!"
        }
    
        FontMetrics {
            id: fontMetrics
            font.family: "Arial"
            font.pointSize: 14
        }
    
        Rectangle {
            anchors.centerIn: parent
            border.width: 1
            width: 300
            height: 200
            Text {
                anchors.centerIn: parent
                font : textMetrics.font
                text: textMetrics.text
            }
        }
    
        Rectangle {
            color: "yellow"
            opacity: 0.5
            anchors.centerIn: parent
            width: textMetrics.width
            height: textMetrics.height
        }
    }
    
    

  • Qt Champions 2018

    What's your goal ?

    You can get the actual text dimensions of an existing Text item with contentWidth and contentHeight.


Log in to reply