js 加载 Jstest111 首字母大写
import "./Js_test.js" as Jstest111
1.js 在程序启动时调用需要使用Component.onCompleted:程序会在qml环境搭建完成后执行
Rectangle{ id:rect2; 100; height: 100; function startup(){ console.log("xxxdddx"); } Component.onCompleted: startup(); }
2.动态创建对象
Component.onCompleted: { var component = Qt.createComponent("SelfDestoryingRect.qml"); for(var i=0; i < 5; i++) { var object1 = component.createObject(container); object1.x = (object1.width + 10) * i; } }
动态删除对象(SelfDestoryingRect.qml),只有动态创建的对象才能删除
import QtQuick 2.0 Rectangle{ id:rect1; 100; height: 100; color: "red"; NumberAnimation on opacity { to:0; duration: 1000; onRunningChanged: { if(!running) { console.log("Destroying"); rect1.destroy(); } } } }
3.qml 共享js
import QtQuick 2.9 import QtQuick.Window 2.2 Window { visible: true 640 height: 480 title: qsTr("Hello World") Calculator{ x:10; y:20; input: 2; } Calculator{ x:40; y:50; input: 3; } }
Calculator.qml
import QtQuick 2.0 import "./factorial.js" as FactorialCalculator Text { id: text1; property int input: 17; //qml 中的 property 的作用是动态为对象添加属性,并且添加的属性可以进行跟踪(值被修改了就会发出信号) text: qsTr("text"+input+ "is" + FactorialCalculator.factorial(input)+"/***=*/"+ FactorialCalculator.factiorialCallCount()); }
factorial.js
.pragma library //共享库标志性 var factorialCount = 0; function factorial(a) { a = parseInt(a); if(a > 0) { console.log(a); return a * factorial(a-1); } console.log("factorialCount:"+factorialCount); factorialCount +=1; return 1; } function factiorialCallCount(){ console.log("factorialCount():"+factorialCount); return factorialCount; }
运行结果
qml: 3
qml: 2
qml: 1
qml: factorialCount:0
qml: factorialCount():1
qml: 2
qml: 1
qml: factorialCount:1
qml: factorialCount():2
先执行3再执行2 栈先进后出????