QML的学习,一直找不到一个很好的参考资料,七零八落,找不到一个渐进的资料。希望自己学习的过程,给大家带来一些帮助。
QML之组件:
依然是main.cpp(当然,没有main.cpp),直接可以使用qmlviewer.exe 直接打开 xml当然可以)
- #include <QtWidgets/qapplication.h>
- #include <qtdeclarative/QDeclarativeview.h>
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- QDeclarativeView *m_qmlView = new QDeclarativeView();
- m_qmlView->setSource(QUrl::fromLocalFile("source.qml")); //load qml file
- m_qmlView->show();
- return a.exec();
- }
我们给我们首先调用的qml为source.qml
- import QtQuick 1.0
-
- Rectangle {
- id: page
- width: 320; height: 240
- color: "lightgray"
-
- Text {
- id: helloText
- text: "Hello world!"
- y: 30
- anchors.horizontalCenter: page.horizontalCenter //居中显示
- font.pointSize: 24; font.bold: true //字体大小
- }
-
- Grid { //grid 摆放 下面的6个 Cell元素
- id: colorPicker
- x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
- rows: 2; columns: 3; spacing: 3 //2行 3列
-
- Cell { cellColor: "red"; onClicked: helloText.color = cellColor } //响应 clicked消息,设置 id为 helloText 的颜色值
- Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
- Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
- Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
- Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
- Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
- }
- }
source.qml使用了 一个非标准的 空间Cell, Cell是另外一个qml文件提供的自定义控件
Cell.qml
- import QtQuick 1.0
-
- Item {
- id: container
- property alias cellColor: rectangle.color
- signal clicked(color cellColor) //clicked 消息
-
- width: 40; height: 25
-
- Rectangle {
- id: rectangle
- border.color: "white"
- anchors.fill: parent
- }
-
- MouseArea {
- anchors.fill: parent
- onClicked: container.clicked(container.cellColor) //响应 clicked消息
- }
- }
库文件:Qt5Declaratived.lib Qt5Guid.lib Qt5Widgetsd.lib Qt5Cored.lib
环境: VS2010 + win7-64位 + Qt5.1.1
运行效果:选择不同的颜色块,字体显示不同颜色
注: qmlviewer.exe 目录为 Qt的bin目录下 (我的相对目录为 Qt5.1.1/5.1.1/msvc2010/bin)
FROM: http://blog.csdn.net/qyee16/article/details/17272057