qtC++调用qml实例.docx
文本预览下载声明
在declarative目录中,有个minehunt范例,实现了在C++中加载QML界面,并用C++来处理QML界面上的鼠标动作.这种思路和传统的GUI相似,感觉比较顺畅.否则运行一个QML,还要使用qmlviewer,上面带一大堆菜单按钮,看着够别扭的.在main函数中,创建了一个QDeclarativeView实例,这个实例负责显示QML界面.接着创建负责处理业务逻辑的MinehuntGame实例,并在view加载QML文件后,将其设置为引擎的上下文对象.这样就可以直接在QML中使用MinehuntGame类中的属性和方法了.感觉设置上下文后,将上下文类实例与QML界面做了融合,QML中的鼠标点击等事件就可以调用类中方法进行处理,并可以绑定到实例的属性.#include QtGui/QApplication#include QtDeclarative/QDeclarativeView#include QtDeclarative/QDeclarativeContext#include QtDeclarative/QDeclarativeEngine#include minehunt.hint main(int argc, char *argv[]){??? QApplication app(argc, argv);??? QDeclarativeView canvas;??? qmlRegisterTypeTileData();//注册TileData类,这个类不需要在QML中实例化.??? MinehuntGame* game = new MinehuntGame();??? canvas.engine()-rootContext()-setContextObject(game);?????? ???? canvas.setSource(QString(qrc:minehunt.qml));??? QObject::connect(canvas.engine(), SIGNAL(quit()), app, SLOT(quit()));? //QML退出,应用程序也退出??? canvas.setGeometry(QRect(100, 100, 450, 450));??? canvas.show();??? return app.exec();}在程序中定义了代表扫雷界面中每个方块的TileData类,用来记录这个方块的状态,如做标记的,被点开的,或有雷的.那么类的实例是如何与QML进行关联同步的呢?在MinehuntGame中定义了一个属性QDeclarativeListPropertyTileData tiles(),与_tiles成员绑定,并在类构造时向tiles中填充多个TileData实例.在QML中可以看到如下声明:??? Grid {??????? anchors.horizontalCenter: parent.horizontalCenter??????? columns: 9; spacing: 1??????? Repeater {??????????? id: repeater??????????? model: tiles??????????? delegate: Tile {}??????? }??? }这样就按MinehuntGame实例中的tiles属性进行构造Grid中的元素了,每个TileData实例生成一个Tile组件.在操作Tile组件时又会反过来调用MinehuntGame中的方法.先看看那个表情图标,点击时会重置界面.??? Image {??????? anchors.bottom: field.bottom; anchors.bottomMargin: 15??????? anchors.right: field.right; anchors.rightMargin: 20??????? source: isPlaying ? MinehuntCore/pics/face-smile.png ://isPlaying,hasWon是MinehuntGame实例中的属性,这里做了绑定,如果实例中的属性发生变化,则图标自动变化??????? hasWon ? MinehuntCore/pics/face-smile-big.png: MinehuntCore/pics/face-sad.png??????? MouseArea { anchors.fill: parent; onPressed: reset() }//点击的时候调用MinehuntGame实例的reset方法,重置雷区,上面也有个关于雷区的绑定,重置后界面自动更新??? }在看看点击雷区的一个方块时的动作触发过程
显示全部