QML 与 C++混合开发
- Qt Quick QML负责UI
- C++负责逻辑与数据处理
- 交互使用Qt的Signal & Slots
QML的基本概念 元素和属性
Rectangle 矩形元素
import QtQuick 2.2
Rectangle {
width: 300
height: 200
opacity: 0.5 //透明度
color: "red"
Text {
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
text: "Hello World"
}
//偏移
Rectangle {
color: "blue"
x: 50; y: 50; width: 100; height: 100
}
}
为了自适应不同的设备,可以使用
anchors.horizontalCenter
anchors.horizontalCenter: pic.horizontalCenter
anchors.top: pic.bottom
anchors.topMargin: 5
import QtQuick 2.2
//Rectangle 高级应用
Rectangle {
property alias text: textItem.text //属性别名
width: 100; height: 30
border.width: 1
radius: 5
smooth: true //圆弧
gradient: Gradient { //渐进变化
GradientStop { position: 0.0; color: "darkGray" }
GradientStop { position: 0.5; color: "black" }
GradientStop { position: 1.0; color: "darkGray" }
}
Text { //文本
id: textItem
anchors.centerIn: parent
font.pointSize: 20
color: "white"
}
}
MouseArea 交互的元素
- Flickable
- FocusScope
-
MouseArea 元素使用 onClicked属性
当然除了onClicked, 还有其他属性onEntered、onExited、onPressed、onReleased
import QtQuick 2.2
//element parent
Rectangle {
color: "#ff0000"
width: 310
height: 210
//element block define as the mousearea
Rectangle {
id: block
width: 60
height: 40
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
Text {
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
text: "block"
}
}
//Interaction
MouseArea {
anchors.fill: block //定义区域
onClicked: {
if (parent.color == "#ff0000")
parent.color = "#ff9900";
else
parent.color = "#ff0000";
}
}
}
为了提升交互体验,要有适当的过渡