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++进行交互的详细介绍可以参考如下链接:
完。
转载于:https://blog.51cto.com/qsjming/1092209