我们在window的D盘安装了Qt Creator后。D:\Qt\Qt5.3.1\Examples这个路径,就是Qt Creator自带的实例路径,我们将从这里开始,慢慢的分析一个个QT实例。这这个系列的文章中,我们将视线集中在QML上。
D:\Qt\Qt5.3.1\Examples\Qt-5.3\quick\animation是我们分析的第一个实例路径,我们先看下面的代码。
该代码的原始版本文件为D:\Qt\Qt5.3.1\Examples\Qt-5.3\quick\animation\animation.qml
import QtQuick 2.0 //我们现在使用新版本的QtQuick
import "../shared" as Examples //这里将导入的../shared目录下的组件合成Examples总组件
Item { //一个组件
height: 680 //高
width: 320 //宽
Examples.LauncherList { //注意这里调用LauncherList的方式
id: ll //id是小写的L
anchors.fill: parent //锚定方式
Component.onCompleted: { //这是一个信号,每个组件都可以调用它,如Item,Image等等
addExample("ColorAnimation", "Interpolates between colors", Qt.resolvedUrl("basics/color-animation.qml")); //这是LauncherList组件中宣布的函数
addExample("PropertyAnimation", "Interpolates between numbers", Qt.resolvedUrl("basics/property-animation.qml"));
addExample("Animators", "Using Animators", Qt.resolvedUrl("basics/animators.qml"));
addExample("Behaviors", "Animates procedural movement", Qt.resolvedUrl("behaviors/behavior-example.qml"));
addExample("Wiggly Text", "Text that wiggles as you drag it", Qt.resolvedUrl("behaviors/wigglytext.qml"));
addExample("Tv Tennis", "Paddles that follow a ball", Qt.resolvedUrl("behaviors/tvtennis.qml"));
addExample("Easing Curves", "Compare available easing curves", Qt.resolvedUrl("easing/easing.qml"));
addExample("States", "Simple states", Qt.resolvedUrl("states/states.qml"));
addExample("Transitions", "Simple states with animated transitions", Qt.resolvedUrl("states/transitions.qml"));
addExample("PathAnimation", "Animate along a path", Qt.resolvedUrl("pathanimation/pathanimation.qml"));
addExample("PathInterpolator", "Interpolates along a path", Qt.resolvedUrl("pathinterpolator/pathinterpolator.qml"));
}
}
}
这段代码是QT的一个示例程序的入口,
第一个知识点:
import "../shared" as Examples 这行,我们可以替换成import "../shared"。当我们这么做的时候,Examples.LauncherList需要替换成LauncherList。这既是说,我们导入多个组件的时候,我们可以单独的导入每个组件,也可以将组件打包成一个导入。注意,当我们使用import "../shared" as Examples这种打包导入的方式时,我们在代码中,是不能直接使用LauncherList的,必须通过Examples.LauncherList来宣布。
第二个知识点:
Component.onCompleted: {
当一个组件的某个属性的信号被触发,而我们需要处理那个触发的信号时,我们就会看到类似的代码结构。这里的Component我们可以看成是组件的一个隐藏属性。当我们声明一个组件如Rectangle时,我们需要调用一些函数,对Rectangle进行初始化,我们就可以使用这个信号来处理。
需要注意的是,Component.onCompleted的触发时间,只和本组件有关。既我们没法保证父子兄弟之间,究竟谁的Component.onCompleted信号会优先触发。
前面的代码用到了LauncherList这个组件,这个组件的源代码为D:\Qt\Qt5.3.1\Examples\Qt-5.3\quick\shared\LauncherList.qml。
import QtQuick 2.0 //例行开头
Rectangle {
color: "#000" //颜色,这里是12位色的表示法,即R4位,G4位,B4位
Component.onCompleted: console.log("Completed Running!") //测试组件信号的试验代码
function addExample(name, desc, url) //声明一个函数
{
myModel.append({"name":name, "description":desc, "url":url})
}
function hideExample()
<