1. 使用Component在QML中嵌入组件
Component是Qt框架或者开发者封装好的、只暴露必要接口的QML类型,可以重复使用。要再QML中嵌入Component的定义,需要使用Component对象。
- Component只能包含一个顶层的Item,而且在这个Item之外不能定义任何的数据,除了Id。
- Component通常用来给一个View提供图形化组件。
- Component不是Item的派生类,而是从QQmlComponent继承而来的,虽然它通过自己的顶层Item为其他的View提供可视化组件,但它本身不是可见元素。
下面是一个简单的在QML文档中定义Component的示例:
Component {
id: itemCompont
Rectangle {
id: compontRect
color: 'blue'
implicitWidth: 200
implicitHeight: 50
signal deleteThis()
Text {
id: interText
anchors.left: parent.left
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
text: qsTr("text")
}
Button {
anchors.margins: 5
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.right: parent.right
text: '删除'
onClicked: {
compontRect.deleteThis()
}
}
}
}
2. 在文件中定义组件
很多时候我们把QML文件定义在一个文件中,方便被其他的QML文件调用。可以直接使用文件名作为组件的名称,在其他的QML文件中使用。上面组件中的代码可以单独定义在一个文件中,本示例的文件名为TestCompont.qml
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.4
Rectangle {
id: compontRect
color: Qt.rgba(0.8, 0.4, 0.4, 1.0)
implicitWidth: 200
implicitHeight: 50
property var currentObject: ''
signal deleteThis(var obj)
// 设置文字的内容
function setCurrentText(textName) {
interText.text = textName
}
Text {
id: interText
anchors.left: parent.left
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
text: qsTr("text")
}