QML Item 元素

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.15

Item {
    id: rootItem
    width: 400
    height: 300
    
    // 作为容器使用
    Item {
        x: 50
        y: 50
        width: 200
        height: 200
        
        Rectangle {
            width: 100
            height: 100
            color: "red"
        }
    }
    
    // 不可见的交互区域
    Item {
        width: 50
        height: 50
        x: 300
        y: 200
        
        MouseArea {
            anchors.fill: parent
            onClicked: console.log("点击了不可见区域")
        }
    }
}

作为组件基类

qml

复制代码
// MyComponent.qml
Item {
    property alias color: rect.color
    property string text
    
    width: 150
    height: 50
    
    Rectangle {
        id: rect
        anchors.fill: parent
        color: "lightblue"
    }
    
    Text {
        text: parent.text
        anchors.centerIn: parent
    }
}

// 使用自定义组件
MyComponent {
    text: "自定义项"
    color: "salmon"
}
相关推荐
千疑千寻~3 天前
【QML】C++访问QML控件
c++·qml
Wallace Zhang4 天前
PySide6 + QML - Charts07 - 使用checkbox选择需要显示的曲线
vscode·pyside6·qml
千疑千寻~4 天前
【QML】自定义控件
qml
Wallace Zhang19 天前
PySide6 + QML - 调试日志01 -告别打印log中文乱码,快速且简单地解决
qt·pyside6·qml
江公望25 天前
Qt QHostInfo::lookupHost()函数,10分钟讲清楚
开发语言·qt·qml
江公望1 个月前
Qt告警clazy-detaching-temporary浅谈
qt·qml
Hi202402171 个月前
为QML程序添加启动Logo:提升用户体验
windows·qt·ui·人机交互·qml·启动logo
紫荆鱼1 个月前
PCL实战项目-软件界面搭建RibbonUI
qt·pcl·用户界面·qml·点云处理
江公望1 个月前
装了新的QtCreator17,没有用Qt5.12自带的QtCreator4,导致QtCreator17无法找到Qt5.12帮助文档
qt·qml
奔跑吧 android1 个月前
【Qt】【1. 版本特性介绍】
qt·cpp·qml