用例 - 在QML中显示文本

如何在QML中显示文本的示例 要显示文本,Qt Quick模块提供了Text类型。对于相关的用途,TextInput和TextEdit类型提供了可编辑的文本控件。有关完整的HTML标记,请参阅Qt WebEngine模块。

显示和格式化文本

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

可以在文本项上设置多个属性来样式化整个文本块。这些属性包括颜色、字体家族、字体大小、粗体和斜体。有关属性的完整列表,请参阅文本类型文档。

可以使用富文本标记来有选择地使用Text项目对文本的特定部分进行样式设置。将Text::textFormat设置为Text.StyledText以使用此功能。更多详细信息可在Text类型的文档中找到。

布局文本

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

示例代码

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
        }
    }
}
../_images/qml-uses-text.png

国际化和可扩展性

处理文本时,应用程序必须考虑各种主题,例如设备的方向和语言设置。

以下页面详细介绍了这些不同的主题。