Text 文本
Text 元素是QML中用于显示文本的基本元素。它可以显示静态文本,也可以通过绑定属性来显示动态文本。Text 元素支持多种文本格式和样式,并且可以通过各种属性来控制文本的显示效果。
常用属性
text: 要显示的文本内容。
Text {
text: "Hello, World!"
}
color: 文本的颜色。
Text {
text: "Hello, World!"
color: "blue"
}
font.family: 字体族。
Text {
text: "Hello, World!"
font.family: "Arial"
}
font.pointSize: 字体大小(以磅为单位)。
Text {
text: "Hello, World!"
font.pointSize: 20
}
font.pixelSize: 字体大小(以像素为单位)。
Text {
text: "Hello, World!"
font.pixelSize: 20
}
horizontalAlignment: 水平对齐方式(如 Text.AlignLeft, Text.AlignRight, Text.AlignHCenter)。
Text {
text: "Hello, World!"
horizontalAlignment: Text.AlignHCenter
}
verticalAlignment: 垂直对齐方式(如 Text.AlignTop, Text.AlignBottom, Text.AlignVCenter)。
Text {
text: "Hello, World!"
verticalAlignment: Text.AlignVCenter
}
wrapMode: 文本换行模式(如 Text.NoWrap, Text.WordWrap, Text.WrapAnywhere)。
Text {
text: "This is a long text that needs to be wrapped."
wrapMode: Text.WordWrap
}
elide: 文本省略模式(如 Text.ElideLeft, Text.ElideRight, Text.ElideMiddle, Text.ElideNone)。
Text {
text: "This is a long text that needs to be elided."
elide: Text.ElideRight
}
style: 文本样式(如 Text.Normal, Text.Outline, Text.Raised, Text.Sunken)。
Text {
text: "Hello, World!"
style: Text.Outline
styleColor: "red"
}
styleColor: 文本样式的颜色(如 Text.Outline 时的轮廓颜色)。
Text {
text: "Hello, World!"
style: Text.Outline
styleColor: "red"
}
textFormat
textFormat 属性值
Text.PlainText: 纯文本格式,不会解析任何 HTML 标签或 Markdown 语法。
Text.RichText: 富文本格式,会解析 HTML 标签。
Text.AutoText: 自动检测文本格式,根据内容自动选择是纯文本还是富文本。
Text.MarkdownText: Markdown 格式,会解析 Markdown 语法。
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
visible: true
width: 640
height: 480
title: "QML Hyperlink in Text Example"
Text {
textFormat: Text.RichText
text: "Visit <a href='https://www.baidu.com'>Fitten Tech</a> for more information."
// 定义一个 JavaScript 函数来处理链接激活事件
function handleLinkActivation(link) {
Qt.openUrlExternally(link)
}
// 使用 JavaScript 函数处理链接激活事件
onLinkActivated: handleLinkActivation(link)
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor // 设置鼠标移入时变成手形光标
acceptedButtons: Qt.NoButton // 不处理鼠标点击事件,只改变光标形状
}
}
}