QT之布局篇

来源:互联网 发布:网络与新媒体概论 资源 编辑:程序博客网 时间:2024/06/01 09:49

QT提供很多种布局的方式,非常灵活,下面介绍的是Qt quick提供几种布局。
分别是:

  • anchors ,锚布局
  • Row ,行布局
  • Column ,列布局
  • Grid ,表格布局
  • Flow ,流式布局

anchors

锚布局是使用Item元素提供的属性anchors来实现的,它是一种相对布局,相对于其他元素的位置来确定自己的位置,基准线有水平中心(horizontalCenter)、垂直中心(verticalCenter)、左(left)、右(right)、上(top)、下(bottom),还有一条基线(baseline)主要用于文本布局的。

通过这些线以及偏移我们就可以很方便的去进行相对布局了,一般使用比较多的就是居中anchors.centerIn = parent,以及充满整个父区域anchors.fill = parent,其它具体可以参考帮助文档

Row

import QtQuick 2.7import QtQuick.Controls 2.0Rectangle {    width: 640    height: 480    color: "#DCDCDC"    Row {        padding: 10        spacing: 20        Rectangle {            width: 100            height: 100            color: "#FF0000"        }        Rectangle {            width: 100            height: 100            color: "#00FF00"        }        Rectangle {            width: 100            height: 100            color: "#0000FF"        }    }}

效果图:
row

Colomn

import QtQuick 2.7import QtQuick.Controls 2.0Rectangle {    width: 640    height: 480    color: "#DCDCDC"    Column {        padding: 10        spacing: 20        Rectangle {            width: 100            height: 100            color: "#FF0000"        }        Rectangle {            width: 100            height: 100            color: "#00FF00"        }        Rectangle {            width: 100            height: 100            color: "#0000FF"        }    }}

效果图:
column

Grid

import QtQuick 2.7import QtQuick.Controls 2.0Rectangle {    width: 640    height: 480    color: "#DCDCDC"    Grid {        padding: 10        spacing: 20        rows: 2        columns: 2        Rectangle {            width: 100            height: 100            color: "#FF0000"        }        Rectangle {            width: 100            height: 100            color: "#00FF00"        }        Rectangle {            width: 100            height: 100            color: "#0000FF"        }    }}

效果图:
grid

表格布局中可以通过属性rows和columns指定几行几列,然后对下面的元素进行排列

Flow

import QtQuick 2.7import QtQuick.Controls 2.0Rectangle {    width: 300    height: 300    color: "#DCDCDC"    Flow {        padding: 10        spacing: 20        flow: Flow.LeftToRight        anchors.fill: parent        Rectangle {            width: 100            height: 100            color: "#FF0000"        }        Rectangle {            width: 100            height: 100            color: "#00FF00"        }        Rectangle {            width: 100            height: 100            color: "#0000FF"        }    }}

效果图:
flow

Flow可以通过flow属性指定布局的方向,默认是Flow.LeftToRight,常用的还有Flow.TopToBottom,当在那个方向无法排列显示更多元素时,它就会折行或折列。

当然还有更多的布局方法,这些方法也可以嵌套使用来完成更加复杂的布局。

原创粉丝点击