QML是一種描述性的腳本語言,文件格式以.qml結尾。語法格式非常像CSS(參考後文具體例子),支持與C++代碼進行交互。是Qt推出的Qt Quick技術的一部分,可以在QT creator中以可視化的方式編輯.qml文件,如下所示:(注:我用的環境爲Ubuntu 12.04 + QT)
下面來寫一個簡單的QML示例程序:
1>用QT creator創建一個QML應用程序
工程名設爲:qmlTest
創建完成後工程目錄如下:
2>編寫代碼
我將要實現的界面及功能如下:
界面包含一個label和一個按鈕,當我點擊quit按鈕時程序退出。
首先我們編寫按鈕的qml實現文件,在工程的qml/qmlTest目錄下添加一個qml文件Button.qml
- import QtQuick 1.0
- Rectangle {
- //identifier of the item
- id: button
- property string label: "button label"
- //these properties act as constants, useable outside this QML file
- property int buttonHeight: 75
- property int buttonWidth: 150
- //the color highlight when the mouse hovers on the rectangle
- property color onHoverColor: "gold"
- property color borderColor: "white"
- //buttonColor is set to the button's main color
- property color buttonColor: "lightblue"
- //set appearance properties
- radius:10
- smooth: true
- border{color: "white"; width: 3}
- width: buttonWidth; height: buttonHeight
- Text{
- id: buttonLabel
- anchors.centerIn: parent
- text: label
- }
- //buttonClick() is callable and a signal handler, onButtonClick is automatically created
- signal buttonClick()
- onButtonClick: {
- console.log(buttonLabel.text + " clicked" )
- }
- //define the clickable area to be the whole rectangle
- MouseArea{
- id: buttonMouseArea
- anchors.fill: parent //stretch the area to the parent's dimension
- onClicked: buttonClick()
- //if true, then onEntered and onExited called if mouse hovers in the mouse area
- //if false, a button must be clicked to detect the mouse hover
- hoverEnabled: true
- //display a border if the mouse hovers on the button mouse area
- onEntered: parent.border.color = onHoverColor
- //remove the border if the mouse exits the button mouse area
- onExited: parent.border.color = borderColor
- }
- //change the color of the button when pressed
- color: buttonMouseArea.pressed ? Qt.darker(buttonColor, 1.5) : buttonColor
- }
修改main.qml的內容以使用剛創建的Button組件,如下:
- import QtQuick 1.1
- Rectangle {
- width: 360
- height: 360
- Text {
- text: qsTr("Hello World")
- }
- Button {
- anchors.right: parent.right
- anchors.top: parent.top
- anchors.margins: 10
- buttonWidth: 100
- buttonHeight: 50
- label: "Quit"
- onButtonClick: {
- Qt.quit();
- }
- }
- }
接下來就可以在C++代碼中進行調用並顯示出來了。
main.cpp:
- #include <QApplication>
- #include "qmlapplicationviewer.h"
- Q_DECL_EXPORT int main(int argc, char *argv[])
- {
- QScopedPointer<QApplication> app(createApplication(argc, argv));
- QmlApplicationViewer viewer;
- viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
- viewer.setMainQmlFile(QLatin1String("qml/qmlTest/main.qml"));
- viewer.showExpanded();
- return app->exec();
- }
點擊運行就可以看到所要的效果了。
有關QML與C++進行交互的詳細介紹可以參考如下鏈接:
完。