上海住房城乡建设厅网站工程机械外贸网站建设
自定义组件是 QML 开发中的核心概念,它允许您创建可重用的 UI 元素和逻辑单元。以下是创建和使用自定义组件的完整方法。
1. 基本自定义组件创建
创建单独组件文件 (推荐方式)
qml
// MyButton.qml(单独一个qml文件)
import QtQuick 2.15Rectangle {id: root// 可自定义属性property string text: "Button"property color textColor: "white"signal clickedwidth: 120; height: 40color: mouseArea.containsMouse ? "#3498db" : "#2980b9"radius: 5Text {anchors.centerIn: parenttext: root.textcolor: root.textColor}MouseArea {id: mouseAreaanchors.fill: parenthoverEnabled: trueonClicked: root.clicked()}
}
内联组件 (适用于简单组件)
qml
Item {component InlineButton: Rectangle {property string textwidth: 100; height: 30color: "lightgray"Text { anchors.centerIn: parent; text: parent.text }}InlineButton { text: "OK" }InlineButton { text: "Cancel" }
}
2. 组件属性与接口
定义属性
qml
// SmartInput.qml
Item {id: root// 基本属性property string placeholder: ""property string text: ""// 带默认值的属性property int maxLength: 100property bool isValid: text.length <= maxLength// 只读属性readonly property bool hasText: text.length > 0// 别名属性property alias cursorPosition: input.cursorPosition// 信号signal accepted(string text)signal validationChanged(bool valid)// 子元素TextInput {id: inputanchors.fill: parenttext: root.textonTextChanged: {root.text = textroot.validationChanged(root.isValid)}onAccepted: root.accepted(text)}
}
使用属性
qml
SmartInput {id: myInputwidth: 200; height: 30placeholder: "请输入用户名"maxLength: 20onAccepted: console.log("输入内容:", text)onValidationChanged: (valid) => {console.log("验证状态:", valid)}
}
3. 组件间通信
方法1: 信号与槽
qml
// ToggleSwitch.qml
Item {id: rootsignal toggled(bool on)property bool on: falseMouseArea {anchors.fill: parentonClicked: {root.on = !root.onroot.toggled(root.on)}}
}// 使用
ToggleSwitch {onToggled: (isOn) => {console.log("开关状态:", isOn)}
}
方法2: 函数调用
qml
// Counter.qml
Item {id: rootproperty int count: 0function increment() {count++}function decrement() {count--}
}// 使用
Counter {id: myCounter
}Button {text: "增加"onClicked: myCounter.increment()
}
4. 动态组件
动态创建
qml
Item {id: containerwidth: 300; height: 300function createDynamicItem() {var component = Qt.createComponent("DynamicItem.qml")if (component.status === Component.Ready) {var obj = component.createObject(container, {"x": Math.random() * 250,"y": Math.random() * 250})}}
}
动态加载 (Loader)
qml
Item {width: 300; height: 300Loader {id: componentLoaderanchors.fill: parentsource: "DynamicComponent.qml"}Button {text: "重新加载"onClicked: {componentLoader.source = ""componentLoader.source = "DifferentComponent.qml"}}
}
5. 高级组件模式
带模型的组件
qml
// ListItem.qml
Rectangle {id: rootwidth: ListView.view ? ListView.view.width : 100height: 50required property string namerequired property string descriptioncolor: mouseArea.containsMouse ? "#f0f0f0" : "white"Column {anchors.fill: parentanchors.margins: 5Text { text: name; font.bold: true }Text { text: description; font.pixelSize: 10 }}MouseArea {id: mouseAreaanchors.fill: parenthoverEnabled: true}
}// 使用
ListView {width: 200; height: 300model: ListModel {ListElement { name: "项目1"; description: "描述1" }ListElement { name: "项目2"; description: "描述2" }}delegate: ListItem {}
}
主题化组件
qml
// ThemedButton.qml
Rectangle {id: root// 主题属性property color primaryColor: "#3498db"property color hoverColor: Qt.darker(primaryColor, 1.2)property color textColor: "white"property string text: "Button"signal clickedwidth: 120; height: 40radius: 5color: mouseArea.containsMouse ? hoverColor : primaryColorText {anchors.centerIn: parenttext: root.textcolor: root.textColor}MouseArea {id: mouseAreaanchors.fill: parenthoverEnabled: trueonClicked: root.clicked()}
}
6. 最佳实践
-
单一职责原则:每个组件应该只负责一个功能
-
明确接口:通过属性和信号定义清晰的组件接口
-
合理命名:使用描述性名称 (如
PrimaryButton而非MyButton) -
文档注释:为组件添加注释说明用法
-
默认值合理:为属性设置合理的默认值
-
性能优化:避免在组件内部进行复杂计算
7. 实际案例:带图标的按钮
IconButton.qml
Item {id: root// 公共APIproperty alias icon: iconImage.sourceproperty alias text: label.textproperty color color: "#3498db"property color hoverColor: Qt.darker(color, 1.2)signal clickedwidth: Math.max(iconImage.width + label.width + 20, 80)height: 40Rectangle {anchors.fill: parentradius: 4color: mouseArea.containsMouse ? root.hoverColor : root.colorRow {anchors.centerIn: parentspacing: 8Image {id: iconImagesourceSize.width: 20sourceSize.height: 20}Text {id: labelcolor: "white"font.pixelSize: 14}}}MouseArea {id: mouseAreaanchors.fill: parenthoverEnabled: trueonClicked: root.clicked()}// 组件行为Behavior on color {ColorAnimation { duration: 200 }}
}
另外qml文件中引用
// 使用示例
IconButton {icon: "qrc:/icons/save.png"text: "保存"onClicked: console.log("保存按钮点击")
}
