玩转QML MVC设计模式应对变化如此简单
Posted IT职场进阶
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了玩转QML MVC设计模式应对变化如此简单相关的知识,希望对你有一定的参考价值。
这一期,和大家简单介绍一下QML里面的MVC设计(Model-View-Controller的缩写,UI设计常用的一种设计模式)。
先放实例demo,过过眼瘾(请忽略美工。。)
实现了2个不同的View,2个不同的Model,2个长的不一样的Delegate。
点击按钮【换Model】可以切换不同的数据,点击【换Delegate】可以切换数据的显示方式。
什么是Delegate呢?简要来说,就是数据张什么样子。如下图,Qt的MVC构成图。
废话不多说,直接上源码:
import QtQuick 2.2
Rectangle {
id: root
width: 500
height: 300
color: "lightblue"
property var currentDelegate: delegate1
property var currentModel: model1
//二组Model
ListModel {
id: model1
ListElement {
name: "张一"
score: "80"
}
ListElement {
name: "张二"
score: "90"
}
ListElement {
name: "张三"
score: "100"
}
}
ListModel {
id: model2
ListElement {
name: "王一"
score: "81"
}
ListElement {
name: "王二"
score: "91"
}
ListElement {
name: "王三"
score: "100"
}
ListElement {
name: "王四"
score: "0"
}
}
//二个Delegate
Component {
id: delegate1
Rectangle {
width: 150; height: 30
color: "yellow"
opacity: 0.3 + 0.7 / currentModel.count * index
Column {
Text {
text: "姓名" + ":" + name
}
Text {
text: "成绩" + ":" + score
}
}
}
}
Component {
id: delegate2
Rectangle {
width: 150; height: 30
color: "red"
opacity: 0.3 + 0.7 / currentModel.count * index
Image {
id: circle
anchors.verticalCenter: parent.verticalCenter
width: 20
height: 20
source: "image/users.png"
}
Text {
anchors.left: circle.right
anchors.leftMargin: 10
anchors.verticalCenter: parent.verticalCenter
text: name + " " + score + "分"
}
}
}
//二个View
Column {
spacing: 10
Text {text: "View1"}
Row {
id: view1
Repeater {
model: currentModel
delegate: currentDelegate
}
}
Text {text: "View2"}
Item {
id: view2
width: 150
height: 90
ListView {
anchors.fill: parent
model: currentModel
delegate: currentDelegate
clip: true
}
}
}
// 换Model/Delegate 按钮
Row {
anchors.bottom: parent.bottom
anchors.bottomMargin: 30
anchors.horizontalCenter: parent.horizontalCenter
spacing: 40
Rectangle {
id: changeModel
width: 100
height: 50
color: "#FFC915"
opacity: mouse1.pressed ? 0.6 : 1
radius: 10
MouseArea {
id: mouse1
anchors.fill: parent
onClicked: {
if (currentModel === model1)
currentModel = model2
else
currentModel = model1
}
}
Text {
anchors.centerIn: parent
text: "换Model"
}
}
Rectangle {
id: changeDelegate
width: 100
height: 50
color: "#FFC915"
opacity: mouse2.pressed ? 0.6 : 1
radius: 10
MouseArea {
id: mouse2
anchors.fill: parent
onClicked: {
if (currentDelegate === delegate1)
currentDelegate = delegate2
else
currentDelegate = delegate1
}
}
Text {
anchors.centerIn: parent
text: "换Delegate"
}
}
}
}
这种MVC框架是不是用起来非常舒服,使用得当的话,一定会帮你完成扩展性强的设计。
如果你对QML感兴趣,那么动起手来,跟着大咖一起玩转QML吧!
以上是关于玩转QML MVC设计模式应对变化如此简单的主要内容,如果未能解决你的问题,请参考以下文章
26.Qt Quick QML-RotationAnimationPathAnimationSmoothedAnimationBehaviorPauseAnimationSequential(代码片段