布局管理
QML提供了多种布局管理器、定位器、基于锚anchors的布局、x,y,width,height等调整用户界面
如果可以通过x y width height 解决,尽量使用,因为布局管理器、定位器锚会占用大量内存和实例化时间
1. 定位器
Column
将子项目排成一列
- spacing属性添加间距
- padding用来设置子与父边界的间距,topPadding、bottomPadding、leftPadding、rightPadding
- 例子
Column{
spacing:2;padding:5;
Rectangle{}
Rectangle{}
Rectangle{}
}
Row
将子项目排成一行
Row{
spacing:2;padding:5;
Rectangle{}
Rectangle{}
Rectangle{}
}
Grid
将子项目排列在网格中,向网格中添加项目会按照从左到右,从上到下进行排列
- 一个Grid默认有四列,但是有无数行,行列通过rows、columns指定
- spacing设置行列的间距,也可以分开rowSpacing、columnSpacing
columns设置初始行数- horizontalItemAlignment: 设置在水平方向的对齐方式
Grid.AlignLeft Grid.AlignRight Grid.AlignHCenter- verticalItemAlignment:
Grid.AlignTop Grid.AlignBottom Grid.AlignVCenter
Grid{
columns:3 //每行三列
spacing:2;padding:5;
Rectangle{}
Rectangle{}
Rectangle{}
Rectangle{}
Rectangle{}
}
Flow
可以从前向后,像流一样布局子项目,超出宽度自动话换行
flow: Flow.LeftToRight Flow.TopToBottom
Rectangle{
width:100;height:100;
Flow{
anchors.fill: parent;
Text{text:"12312312321"} //文字超出自定换行
Text{text:"12312312321"}
Text{text:"12312312321"}
Text{text:"12312312321"}
}
}
过渡器 Transition
定位器添加删除一个子Item时,可以使用Transition,添加动画效果 上述四个定位器都有 add move
populate属性
Column{
Rectangle{color:"red"}
Rectangle{color:"blue"}
Rectangle{id:greenRec;color:"green"}
move:Transition{NumberAnimation{properties:"x,y";duration:1000;}
focus:true
keys.onSpacePressed:greenRec.visible =! greenRec.visible
}
Positioner
为定位器的子项目提供索引信息
Repeater
创建大量相似项目
包含一个model、一个delegate,委托用来将模型中的item进行显示
Rectangle{
width:100;height:100;color:"black"
Grid{
x:5;y:5;
rows:5;columns:5;
Repeater{
model:12
Rectangle{Text{text:index}} //使用Rectangle作为委托,文本中使用index显示每个item的编号 count获取创建的数量
}
}
}
2 基于锚的布局
每个Item都有一组无形的锚线:
left、right、top、bottom、horizontalCenter、verticalCenter、baseline
7条锚线分别对应了Item的anchors的相关属性
Item{
Rectangle{id:rect1;Text{anchors.centerIn:parent}}
Rectangle{
id:rect2
anchors.left:rect1.right //该Rectangle锚定了rect1的右边界
anchors.leftMargin:5; //该Rectangle距离Rect1的右侧5像素
anchors.top:rect1.bottom
Text{anchors.centerIn:parent}
}
}
运行时改变锚
AnchorChanges 运行时修改项目的锚,需要在状态State中进行,需要时可以使用PropertyChanges完成、使用AnchorAnimation提供动画效果
Rectangle{
id:window
Rectangle{id:myRect}
states:State{
name:"reanchored"
AnchorChanges{
target:myRect
anchors.top:window.top
anchors.bottom:window.bottom
}
PropertyChanges{
target:myRect
anchors.topMargin:10
anchors.bottomMargin:10
}
}
transition:Transition{
AnchorAnimation{
duration: 1000
}
}
MouseArea{
anchors.fill:parent;
onClicked:window.state="reanchored"
}
}
3.布局管理器
QML的布局管理器和QWidget的很类似
需要引入 import QtQuick.Layouts
RowLayout、ColumnLayout、GridLayout、StackLayout
对齐方式:Layout.Alignment :
Qt::AlignLeft、
Qt::AlignRight、
Qt::AlignTop、
Qt::AlignBottom、
Qt::AlignHCenter、
Qt::AlignVCenter
可变大小:
Layout.fillWidth: true|false
Layout.fillHeight: true|false
间距:
spacing rowSpacing columnSpacing
网格布局坐标
Layout.row、Layout.column
行或列的跨度
Layout.rowSpan、 Layout.columnSpan
大小约束
最小宽高:minimumWidth、 minimumHeight
最佳宽高:preferredWidth、preferredHeight
最大宽高:maximumWidth、 maximumHeight
并将对应的Layout.fillWidth\Layout.fillHeight设置为true