6.3布局管理
1.定位器:基本Qt Quick图形元素提供了一组标准的定位器,Column,Row,Grid和Flow
Column:垂直排列项目
spacing: 间距
Row:水平排列项目
spacing: 间距
Grid:网格,默认4列,无限多行
rows:行数
columns:列数
spacing: 间距
Flow:流式排列,自动换行
flow:流向Flow.LeftToRight(default)Flow.TopToBottom
import QtQuick 2.0
Grid{
columns: 3
spacing: 2
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
Rectangle { color: "cyan"; width: 50; height: 50 }
Rectangle { color: "magenta"; width: 10; height: 10 }
}
2.重复器Repeater
Repeater: 用来创建大量相似的元素
model:
delegate:用来将模型中的每一个条目分别实例化
import QtQuick 2.0
Rectangle{
width: 400; height: 400; color: "black"
Grid{
x: 5; y: 5
rows: 5; columns: 5; spacing: 10
Repeater{
model: 24
Rectangle{
width: 70; height: 70
color: "lightgreen"
Text {
text: index
font.pointSize: 30
anchors.centerIn: parent
}
}
}
}
}
3.切换:切换可以使在定位器中进行添加,移入或者删除项目时具有动画效果
定位器都有add和move属性,需要分配一个Transition对象
Flow{
id: positioner
move:Transition{
NumberAnimation{
properties: "x, y"
ease: "easeOutBounce"
}
}
}
4.锚(anchor)的布局
每一个项目无形的锚线:left, horizontalCenter, right, top, verticalCenter, baseline, bottom
锚边距:rightMargin, topMargin, leftMargin, bottomMargin anchor.margins
锚偏移:horizontalCenterOffset, verticalCenterOffset, baselineOffset
baseline: 假想线,文本坐落这条线,如无文本,与top相同
anchors.fill: 等价于使用了4个直接的锚
Image {id:pic;...}
Text {
id: label
anchors.horizontalCenter: pic.horizontalCenter
anchors.top: pic.bottom
anchors.topMargin: 5
...
}
6.4基本可视元素
1.Item:QML中所有可视项目都继承自Item,定义了可视化项目所有属性
children: 可见孩子列表
resources: 不可见资源
data: 默认属性,可增加可视项目和资源
opacity:透明度
z: 堆叠顺序,值越大在越上面
2.Rectangle:用来使用纯色或渐变填充区域,也经常用来放置其他项目
color:纯色填充
gradient: Gradient元素渐变填充
border.color: 边框颜色
border.width: 边框宽度
radius:圆角矩形
3.Text: 显示纯文本或者富文本
wrapMode: 设置换行
elide: 单行,为超出宽度的文本提供...
font: 设置字体相关属性
horizontalAlignment: 水平对齐方式
verticalAlignment: 垂直对齐方式
style:文本样式
Text::onLinkActivaed(string link): 单击文本嵌入连接发送信号
4.TextEdit:显示一块可编辑的,格式化的文本
focus: 设置焦点
5.TextInput:显示单行的可编辑的纯文本
echoMode:可设置输入密码
validator: 验证器 IntValidator, DoubleValidator, RegExpValidator
TextInput{
validator: IntValidator{bottom: 11; top: 31}
}
6.5事件处理
1.MouseArea:不可见项目,通常和可见项目配合使用来提供鼠标事件处理
enabled:是否启用鼠标处理
pressed: 是否在mousearea按住了鼠标按钮
containsMouse:是否有鼠标光标在MouseArea上
hoverEnabled: 是否启用鼠标悬停事件处理
onClicked(),onDoubleClicked(),onPressed(),OnReleased(),onPressAndHold()
onPositionChanged(),onEntered(),onExited()
MouseEvent: 很多MouseArea的信号中都包含一个鼠标事件参数
MouseArea::onClicked(MouseEvent mouse)
x,y: 鼠标位置
button: 鼠标按键Qt.LeftButton,Qt.RightButton,Qt.MiddleButton
modifiers: 组合键
拖拽:
drag.target: 拖动项目id
drag.active:获取项目当前是否正在被拖动的信息
drag.axis:拖动的方向
drag.minimumX,drag.minimumY,drag.maximumX,drag.maximumY: 限制拖动距离
2.按键处理:所有基于Item的可见元素都可以通过Keys附加属性进行按键处理
Keys.onPressed(KeyEvent event)
Keys.onReleased(KeyEvent event)
KeyEvent:这些处理器大多包含一个KeyEvent参数,提供该键盘时间的信息
event.accepted:设置为true防止事件向上层传播
KeyNavigation附加属性实现导航
Item::activeFocus: 是否具有活动焦点
focus: 设置为true来获得焦点
FocusScope:创建焦点作用域
3.定时器Timer
interval:时间间隔,单位ms默认1000ms
repeat:是否重复触发,如果为false,触发一次,running设置为false,默认false
running:为true时开启定时器,默认false
onTriggered():定时器触发时会执行的信号处理函数
定时器运行过程中属性被更改,时间重置
4.使用Loader动态加载组件
Loader元素用来动态加载可见的QML组件
加载QML文件,使用source属性
加载组件对象,使用sourceComponent属性
从加载项目中发射信号可以使用Connections元素接收
Item{
width:100; height: 100
Loader{
id: myLoader
source: "MyItem.qml"
}
Connections{
target: myLoader.item
onMessage: console.log(msg)
}
}
6.6图像、状态和动画
1.渐变:
QML使用Gradient项目来定义一个渐变
渐变中的一组颜色用GradientStop子项目定义
2.图片Image:用来声明式用户界面中显示图片
source:URL
fillMode:填充模式
asynchronous:加载大图片异步加载
sourceSize:真实像素数量
3.边界图片BorderImage:通过缩放或者平铺创建超出图片的边界
horizontalTileMode:水平缩放模式
verticalTileMode:垂直缩放模式
border:边界线
4.动态图片AnimatedImage
currentFrame:当前帧
frameCount:总长度
playing:开始
paused:暂停
5.缩放、旋转和平移
Item元素
scale:缩放
rotation:旋转
transformOrigin:缩放旋转原点,默认Center
transform:Transform元素列表
Rotation
axis.x:X轴
axis.y:Y轴
axis.z:Z轴
origin.x,origin.y:原点
Scale
origin.x,origin.y:原点
xScale,yScale:比例因子
Translate
x,y:偏移量
6.QML状态:
states:State状态列表
State
PropertyChanges:为其他项目增加附加属性
when:自动恢复状态
7.QML动画
PropertyAnimation on x(动画 on 属性)
from:起点
to:终点
duration:间隔
loops:循环次数,Animation.Infinite无限循环
Behavior on x
行为动画:特定属性值改变时应用的动画
Behavior on x { PropertyAnimation { duration: 500}}
onClicked:PropertyAnimation{...}
在信号处理器中的动画
独立动画
默认没有运行,用running属性或start和stop明确运行
8.切换:状态改变时的动画
transitions: list[Transition]
9.属性动画元素:PropertyAnimation子元素
NumberAnimation
colorAnimation
RotationAnimation
Vector3dAnimation
SmoothedAnimation
SpringAnimation
ParentAnimation
AnchorAnimation
10.组合动画
一旦独立动画放入SequentialAnimation或ParallelAnimation,就不能独立开启或停止
ParallelAnimation
SequentialAnimation
PauseAnimation
11.弹动效果Flickable元素
将子项目设置在一个可以拖拽和弹动的界面上,使得子项目视图可以滚动
clip: true隐藏超出区域的内容
visibleArea.xPosition: 0.0~1.0-widthRatio
visibleArea.widthRatio
visibleArea.yPosition: 0.0~1.0-heightRatio
visibleArea.heightRatio
12.翻转效果Flipable元素
同时使用Rotation,State,Transition等元素产生翻转效果
Flipable
front:正面
back: 反面
6.7QML中的模型/视图
1.ListModel
ListElement:list项
2.XmlListModel
source
query
XmlRole
query:"title/string()" "id/number()" 属性"@type/string()"
3.VisualItemModel
允许QML项目作为模型
4.ListView:水平或垂直列表中排列条目,继承自Flickable项目
model:指定model
delegate:委托
currentIndex:当前选择索引
index: 索引
ListView {
id: view
width: 180; height: 200
Component {
id: contactsDelegate
Rectangle {
id: wrapper
width: 180
height: contactInfo.height
color: index % 2 == 0 ? "cyan" : "green";
Text {
id: contactInfo
text: name + ": " + number
color: wrapper.ListView.isCurrentItem ? "red" : "black"
}
MouseArea {
anchors.fill: parent
onClicked: view.currentIndex = index
}
}
}
model: ListModel {
ListElement {
name: "Bill Smith"
number: "555 3264"
}
ListElement {
name: "John Brown"
number: "555 8426"
}
ListElement {
name: "Sam Wise"
number: "555 0473"
}
}
delegate: contactsDelegate
focus: true
}
5.GridView:排列网格
cellWidth
cellHeight
6.PathView:路径排列
path
PathLine,PathQuad,PathCubic
7.WebView
url
6.8QML和C++混合编程
1.QQuickView:widget方式使用QML组件
Qt4.x是QDeclarativeView
Qt5.x是QQuickView
view.setSource(QUrl::fromLocalFile("../application.qml"))
2.QQmlApplicationEngine:QML引擎提供执行QML代码的环境
Qt4.x是QDeclarativeEngine
Qt5.x是QQmlEngine
engine.load(QUrl(QStringLiteral("qrc:/main.qml")))
3.QQmlComponent:一个组件封装了一个QML文件
4.QQmlContext:允许应用程序将数据暴露给由引擎创建的QML组件
5.从C++加载一个QML组件
可使用QQmlComponent和QQuickView
QObject * object = component.create()
QObject * objcet = view.rootObject()
读取和修改属性
object->setProperty("width", 500)
QQmlProperty(object, "width").write(500)
QQuickItem * item = qobject_cast
item->setWidth(500)
绑定QML信号
QObjcet::connect(item, SIGNAL(qmlSignal(QString), &myClass, SLOT(cppSlot(QString))));
object->objectName()
object->findChild
6.在QML组件中嵌入C++对象
view.rootContext->setContextProperty("data", &data)
engine.rootContext->setContextProperty("data", &data)
在QML文件就能直接读取和修改data
text: data.getName()
Connections{
target: data
//data有一个dataChanged()信号
onDataChanged:console.log("data changed")
}
7.C++中调用QML组件函数
QMetaObject::invokeMethod(...)
QObject *object = component.create();
QVariant returnValue;
QVariant msg = "Hello from C++"
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnValue),
Q_ARG(QVariant, msg));
Q_RETURN_ARG()和Q_ARG()参数必须指定为QVariant类型
8.定义一个新的QML元素
可以在QML中进行定义,也可以使用C++类来定义
当使用C++类定义的元素创建一个QML对象时,就是创建了一个基于QObject的C++类实例并且设置了属性
定义属性:
class ImageViewer :public QObject
{
Q_OBJECT
Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
public:
void setSource(const QUrl &url);
QUrl source() const;
signals:
void sourceChanged();
};
QML引擎注册:
qmlRegisterType
9.QML中的全局对象
帮助搜索Qt
枚举变量:
Qt::MouseButton
类型:
color,rect,point,size,vector3d
date/time:
动态对象创建:
补充:布局管理器
GridLayout:和Grid定位器相比,可以使用如下附加属性:
Layout.row
Layout.column
Layout.rowSpan
Layout.columnSpan
Layout.minimumWidth
Layout.minimumHeight
Layout.preferreWidth
Layout.perferredHeight
Layout.maximumWidth
Layout.maximumHeight
Layout.fillWidth
Layout.fillHeight
Layout.alignment
和Grid定位器相比,GridLayout可以对内部布局进行管理,而Grid只能进行定位,简单就用Grid了
ColumnLayout和RowLayout是GridLayout的一种特殊情况
StackLayout
一次只显示一个子项目,通过currentIndex指定