Item 是 QML 中最基础的视觉元素,作为所有可视组件的基类,它提供了基本的属性和功能,但不具有可视化表现(没有颜色、边框等)。
核心属性
属性 | 类型 | 默认值 | 描述 |
---|---|---|---|
x | real | 0 | X 坐标位置 |
y | real | 0 | Y 坐标位置 |
width | real | 0 | 宽度 |
height | real | 0 | 高度 |
z | real | 0 | Z 轴顺序(堆叠顺序) |
opacity | real | 1.0 | 透明度(0.0-1.0) |
visible | bool | true | 是否可见 |
enabled | bool | true | 是否接受用户输入 |
clip | bool | false | 是否裁剪子项超出部分 |
布局相关属性
属性 | 类型 | 描述 |
---|---|---|
anchors | AnchorLine | 锚定系统 |
baselineOffset | real | 基线偏移 |
transform | list<Transform> | 变换列表 |
transformOrigin | enumeration | 变换原点 |
常用信号
信号 | 描述 |
---|---|
onXChanged | X 坐标改变时触发 |
onYChanged | Y 坐标改变时触发 |
onWidthChanged | 宽度改变时触发 |
onHeightChanged | 高度改变时触发 |
onChildrenChanged | 子项变化时触发 |
基本用法
qml
import QtQuick 2.15Item {id: rootItemwidth: 400height: 300// 作为容器使用Item {x: 50y: 50width: 200height: 200Rectangle {width: 100height: 100color: "red"}}// 不可见的交互区域Item {width: 50height: 50x: 300y: 200MouseArea {anchors.fill: parentonClicked: console.log("点击了不可见区域")}}
}
作为组件基类
qml
// MyComponent.qml
Item {property alias color: rect.colorproperty string textwidth: 150height: 50Rectangle {id: rectanchors.fill: parentcolor: "lightblue"}Text {text: parent.textanchors.centerIn: parent}
}// 使用自定义组件
MyComponent {text: "自定义项"color: "salmon"
}