显示文本
要显示文本, Qt Quick 模块提供了“Text”类型。对于相关用途,TextInput 和TextEdit 类型提供了可编辑的文本控件。如需使用完整的HTML标记,请参阅Qt WebEngine 模块。
显示和格式化文本
要在 QML 中显示文本,请创建一个 Text 项,并将 text 属性设置为要显示的文本。此时,Text 项将显示该文本。
可以通过设置 Text 项的若干属性来设置整个文本块的样式,包括颜色、字体家族、字号、加粗和斜体。有关属性的完整列表,请参阅Text 类型的文档。
可使用类似标记语言的富文本,通过 Text 项对文本的特定部分进行选择性样式设置。将Text::textFormat 设置为 Text.StyledText 即可使用此功能。更多详细信息请参阅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
}
}
}
国际化和可扩展性
在处理文本时,应用程序必须考虑各种因素,例如设备的方向和语言设置。
以下页面将详细介绍这些主题。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.