显示文本和设置文本格式

要在 QML 中显示文本,请创建一个文本项,并将 text 属性设置为要显示的文本。文本项现在将显示该文本。

可以在 Text 项上设置多个属性来设置整个文本块的样式。这些包括颜色、字体系列、字体大小、粗体和斜体。

富文本(如标记)可用于有选择地设置文本特定部分的样式,其中包含 Text 项。将 Text::textFormat 设置为 Text.StyledText 以使用此功能

设置文本布局

默认情况下,Text 会将文本显示为单行,除非它包含嵌入的换行符。若要换行,请设置 wrapMode 属性,并为文本指定要换行的显式宽度。如果未显式设置宽度或高度,则读取这些属性将返回文本边框的参数(如果已显式设置宽度或高度,则仍可使用paintedWidth和paintedHeight)。考虑到这些参数,文本可以像任何其他项目一样定位。

例:

import QtQuick

Item {
    id: root
    width: 480
    height: 320

    Rectangle {
        color: "#272822"
        width: 480
        height: 320
    }

    Column {
        spacing: 20

        Text {
            text: 'I am the very model of a modern major general!'

            // color can be set on the entire element with this property
            color: "yellow"

        }

        Text {
            // For text to wrap, a width has to be explicitly provided
            width: root.width

            // This setting makes the text wrap at word boundaries when it goes
            // past the width of the Text object
            wrapMode: Text.WordWrap

            // You can use \ to escape quotation marks, or to add new lines (\n).
            //  Use \\ to get a \ in the string
            text: 'I am the very model of a modern major general. I\'ve information \
                  vegetable, animal and mineral. I know the kings of england and I \
                  quote the fights historical; from Marathon to Waterloo in order categorical.'

            // color can be set on the entire element with this property
            color: "white"

        }

        Text {
            text: 'I am the very model of a modern major general!'

            // color can be set on the entire element with this property
            color: "yellow"

            // font properties can be set effciently on the whole string at once
            font { family: 'Courier'; pixelSize: 20; italic: true; capitalization: Font.SmallCaps }

        }

        Text {
            // HTML like markup can also be used
            text: '<font color="white">I am the <b>very</b> model of a modern <i>major general</i>!</font>'

            // This could also be written font { pointSize: 14 }. Both syntaxes are valid.
            font.pointSize: 14

            // StyledText format supports fewer tags, but is more efficient than RichText
            textFormat: Text.StyledText
        }
    }
}