Qml Text Item如何设置行间距?

How to set the line spacing for Qml Text Item?

我搞不懂这个。我的意思是 Qml 文本项中文本行之间的垂直间距。我不能使用 Rich Text,而且 GridLayout 似乎破坏了我的环绕、水平对齐和检查截断的能力。这是在一个矩形里面。

Text{   
        width:10
        wrapMode: Text.Text.Wrap
        text:"This will be broken into multiple lines. How could I set the vertical spacing between them?"
     }

我的意思是:

VS

一个好习惯就是check the documentation. Browsing through it, you could see a property called lineHeight。我相信这就是您要找的。来自文档:

lineHeight : real

Sets the line height for the text. The value can be in pixels or a multiplier depending on lineHeightMode.

他们还告诉你如何使用它

The default value is a multiplier of 1.0. The line height must be a positive value.

使用 lineHeight 作为乘数可以让您在 MSWord 中模仿以下行间距枚举。

Single
1.5 lines
Double
Multiple

这是一个例子:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    visible: true
    width: 200
    height: 300
    
    Text {
        id: text
        width: 175
        anchors.centerIn: parent
        
        //  text: "HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO HELLO"
        text: "Cat ipsum dolor sit amet, sleep nap. You call this cat food. Push your water glass on the floor."
        
        font.family: "Monaco"    // Monaco ❤️
        wrapMode: Text.WordWrap  // Make the text multi-line
        horizontalAlignment: Text.AlignHCenter

        //  lineHeight: 1.0  // single-spacing (default)
        lineHeight: 1.5  // 1.5 line-spacing
        //  lineHeight: 2.0  // double-spacing
        //  lineHeight: 3.0  // triple-spacing
        
    }
}

以下是使用 lineHeight 的不同值的结果(在典型的 MacOS 上)

单倍行距

1.5 倍,双倍 (2x),三倍 (3x)


但是,如果您想模仿其他行间距枚举:

At least
Exactly

您需要修改像素高度。您可以通过将 lineHeightMode 设置为 Text.FixedHeight 来实现。像这样

Window {
    visible: true
    width: 200
    height: 300
    
    Text {
        id: text
        width: 175
        anchors.centerIn: parent
        
        text: "Cat ipsum dolor sit amet, sleep nap. You call this cat food. Push your water glass on the floor."
        
        font.family: "Monaco"    // Monaco ❤️
        wrapMode: Text.WordWrap  // Make the text multi-line
        
        
        lineHeightMode: Text.FixedHeight
        lineHeight: 6            // exaggerated, text will be scrunched up
        
    }
}

刚好 6