QML 自定义组件外观和行为
在 QML 中,有许多属性可以用来自定义组件的外观和行为。以下是主要分类和常用属性:
1. 外观定制属性
基本视觉属性
-
颜色相关:
-
color- 基础颜色 -
border.color- 边框颜色 -
border.width- 边框宽度
-
-
形状相关:
-
radius- 圆角半径 -
clip- 是否裁剪超出部分
-
背景和前景
-
background- 定义背景元素 -
contentItem- 定义主要内容 -
overlay- 定义覆盖层
文本显示
-
font- 字体属性(family, pixelSize, bold等) -
horizontalAlignment/verticalAlignment- 对齐方式 -
elide- 文本省略方式
2. 行为定制属性
交互属性
-
enabled- 是否启用组件 -
hoverEnabled- 是否启用悬停检测 -
focus- 是否获得焦点 -
pressAndHoldInterval- 长按识别时间
状态相关
-
state- 当前状态 -
states- 定义状态列表 -
transitions- 定义状态转换动画
视图行为
-
spacing- 子项间距(Row/Column等布局) -
model- 数据模型 -
delegate- 项目委托 -
highlight- 高亮项定义
3. 布局和尺寸属性
尺寸控制
-
width/height- 显式尺寸 -
implicitWidth/implicitHeight- 隐式尺寸 -
minimumWidth/maximumWidth- 最小/最大尺寸
定位属性
-
anchors- 锚定系统 -
x/y- 绝对位置 -
z- z轴顺序
4. 动画和效果属性
动画
-
Behavior- 属性变化行为 -
NumberAnimation- 数值动画 -
PropertyAnimation- 属性动画
视觉效果
-
opacity- 透明度 -
scale- 缩放比例 -
rotation- 旋转角度 -
layer.effect- 应用着色器效果
5. 自定义组件示例
qml
// 自定义按钮示例
Button {id: customBtnwidth: 120height: 40// 背景定制background: Rectangle {color: customBtn.down ? "dodgerblue" : (customBtn.hovered ? "lightblue" : "steelblue")radius: 5border.width: 1border.color: "navy"}// 内容定制contentItem: Text {text: "提交"color: "white"horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenterfont.bold: true}// 悬停效果hoverEnabled: true// 点击动画Behavior on scale {NumberAnimation { duration: 100 }}onPressed: scale = 0.95onReleased: scale = 1.0
}
示例:自定义按钮背景
Button {text: "Click Me"width: 120height: 40// 自定义背景background: Rectangle {color: parent.down ? "darkblue" : (parent.hovered ? "blue" : "lightblue")radius: 5 // 圆角border.width: 1border.color: "navy"}
}
delegate(委托)
用于 ListView、GridView 等视图组件,定义每个数据项的显示方式。
示例:自定义 ListView 的项
ListView {width: 200height: 200model: ["Apple", "Banana", "Orange"] // 数据模型// 自定义 delegate(每个数据项的显示方式)delegate: Rectangle {width: parent.widthheight: 40color: index % 2 === 0 ? "white" : "#f0f0f0" // 交替行颜色Text {text: modelData // 数据内容anchors.centerIn: parentfont.pixelSize: 16}}
}
contentItem(内容项)
用于定义控件的核心内容(如 Button 的文本、ComboBox 的当前选项等)。
示例:自定义按钮的文本样式
Button {width: 150height: 50// 自定义 contentItem(按钮的内容)contentItem: Text {text: "Submit"color: "white"font.bold: truefont.pixelSize: 16horizontalAlignment: Text.AlignHCenterverticalAlignment: Text.AlignVCenter}// 自定义背景background: Rectangle {color: parent.down ? "darkgreen" : "green"radius: 5}
}
这些属性组合使用可以创建出高度定制化的QML组件,满足各种UI设计需求。
