QML中的Label組件是構建用戶界面時最常用的文本顯示控件之一,它繼承自Text元素但提供了更豐富的UI特性和主題集成支持。本文將全面介紹Label的核心功能、屬性配置、使用技巧以及與Text組件的區別,幫助開發者高效構建美觀的文本界面。
Label組件基礎
Label是Qt Quick Controls 模塊提供的文本顯示控件,它具有以下特點:
- ?自動適配系統主題?:默認遵循應用程序的主題設置
- ?更豐富的樣式定制?:支持背景、內邊距等UI特性
- ?優化的排版處理?:內置更好的文本布局管理
- ?控件級功能?:提供焦點策略、狀態管理等控件特性
基本使用需要先導入模塊:
import QtQuick.Controls 2.15
最簡單的Label定義:
Label {text: "Hello QML"
}
核心屬性詳解
1. 文本內容與樣式
- ?text?:顯示的文字內容,支持靜態文本和動態綁定
- ?color?:文本顏色,支持顏色名稱或十六進制值
- ?font?:字體樣式組,包含多個子屬性:
font {family: "Arial" // 字體pixelSize: 16 // 字號bold: true // 加粗italic: true // 斜體underline: true // 下劃線 }
2. 布局與對齊
- ?horizontalAlignment?/?verticalAlignment?:水平和垂直對齊方式
- ?wrapMode?:文本換行模式(NoWrap/WordWrap/WrapAnywhere)
- ?elide?:文本溢出處理(ElideLeft/ElideMiddle/ElideRight)
- ?padding?:內邊距設置,支持統一或分邊設置:
padding: 10 // 統一設置 // 或分邊設置 topPadding: 5 leftPadding: 10
3. 背景與裝飾
Label特有的背景設置能力:
background: Rectangle {color: "lightgray"radius: 5 // 圓角border.color: "gray"
}
高級功能應用
1. 富文本支持
通過設置textFormat
屬性支持富文本顯示:
Label {text: "<b>粗體</b>和<i>斜體</i>文本"textFormat: Text.RichTextonLinkActivated: Qt.openUrlExternally(link)
}
2. 多語言國際化
使用qsTr()
函數實現多語言支持:
Label {text: qsTr("歡迎使用")
}
?示例代碼:
import QtQuick
import QtQuick.ControlsWindow {width: 1024height: 768visible: truetitle: qsTr("Hello World")Label {id: backgroundLabelanchors.fill: parentbackground: Image {source: "kun.jpg"}}// Text文本Label {id: label1width: 300height: 300text: "普惠體 3.0 55 Regular ABCDEFG 1234546789"font.family: "阿里巴巴普惠體 3.0 55 Regular"font.pixelSize: 32font.bold: truefont.underline: true //下劃線font.wordSpacing: 30 //字體間距color: "red"wrapMode: Text.WordWrap //根據word換行leftPadding: 10 //設置左邊距10像素horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter}Label {id: label2width: 220height: 50anchors.top: label1.bottomanchors.topMargin: 10anchors.left: parent.leftbackground: Rectangle {color:"#FFFF00"}text: "Hello World123456"font.pixelSize: 32color: "blue"horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter// topInset: 20// leftInset: 30 //設置背景間隔,跟QSS的padding-left差不多吧style: Text.Raised //字體風格elide: Text.ElideRight //超出右邊范圍省略}Label {id: label3width: 220height: 50anchors.top: label2.bottomanchors.topMargin: 10anchors.left: parent.leftanchors.leftMargin: 20background: Rectangle {color:"#00FF00"}text: "Hello World123456"font.pixelSize: 32color: "blue"horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter// leftInset: 30clip: true //文本字體太大,超出文本范圍截斷}Label {id: label4width: 140height: 60anchors.centerIn: parentbackground: Image {source: "qt_logo.png" //如果是資源文件,要賦值資源文件的地址}}Label {id: label5width: 50height: 50anchors.top: label4.bottomanchors.topMargin: 30anchors.horizontalCenter: parent.horizontalCenterbackground: Image {id: label5Imagesource: "settings.png"}MouseArea {anchors.fill: label5onPressed: {label5Image.opacity = 0.5}onReleased: {label5Image.opacity = 1}onClicked: {console.log("label5 clicked!")}}}}
效果展示: