动态创建qml

qml 动态创建 对象(2011-03-06 21:35)
分类: QML

main.cpp =====call====> main.qml ==call==> componentCreation.js ====call===> Sprite.qml

根据官方文档改写。

========================= main.cpp ============================
#include<QtGui/QApplication>

#include"qmlapplicationviewer.h"i

ntmain(intargc,char*argv[])

{

QApplicationapp(argc,argv);

QmlApplicationViewerviewer

;viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);

viewer.setMainQmlFile(QLatin1String("qml/SensorControl/main.qml"));

viewer.showExpanded();

returnapp.exec()

;}


========================main.qml==================================

importQtQuick1.0

import"componentCreation.js"asMyScript

Rectangle{

id:appWindowwidth:400;

height:400

color:"blue"

propertyvariantobj;
Rectangle{

id:window1

width:20;

height:20

color:"red"

MouseArea

{

id:mouseArea1

anchors.fill:parentonClicked:{

window2.visible=false;/*www.visible=true*/}

}

Component.onCompleted:{mouseArea1.clicked.connect(MyScript.jsFunction)}}

Rectangle{

id:window2width:120;

height:120color:"yellow";

x:40;y:40

Rectangle

{id:window3width:50;

height:50color:"green";}

}

Rectangle{

id:window4width:50;height:50color:"green";x:window2.x+20;
y:window2.y+20;

Rectangle{

id:window5width:20;height:20color:"black"

MouseArea{id:mouseArea5anchors.fill:parentonClicked:{

window2.visible=true;/*www.visible=true;*/window2.x=window2.x+10;obj.y=10;}

}}}
Component.onCompleted:

{

obj=MyScript.createSpriteObjects(window2);

obj.y=200;/*newWindow.destroy(1000);*/}

}


========================componentCreation.js==========================

varcomponent;

functioncreateSpriteObjects(parentId)

{

component=Qt.createComponent("Sprite.qml");i

f(component.status==Component.Ready)r

eturnfinishCreation(parentId);

elsecomponent.statusChanged.connect(finishCreation);}

functionfinishCreation(parentId)

{if(component.status==Component.Ready)

{varsprite=component.createObject(parentId/*appWindow*/,{"x":0,"y":0});if

(sprite==null){//ErrorHandlingconsole.log("Errorcreatingobject");}

sprite.y=200;returnsprite;}

elseif(component.status==Component.Error)

{//ErrorHandlingconsole.log("Errorloadingcomponent:",component.errorString());}}

functionjsFunction(){console.log("CalledJavaScriptfunction!") }

========================= Sprite.qml ==================
importQtQuick1.0

Rectangle

{width:50;height:50;color:"red"

MouseArea

{id:mouse_area1anchors.fill:parent

onEntered:parent.width+=10;

onExited:parent.width-=10;}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值