一.前言
在学习QML的过程中,楼主总感觉QML和JS更为洽和,有一种QML的壳,JS是内在的感觉,即是QML负责界面,js负责逻辑,于是就记录一下QML调用js的方式
二.调用举例
先构建一个测试界面,通过按钮来触发调用
1.调用当前qml中的js函数
1.1编写js函数
2.调用逻辑
Button{
id:btn_1
text: "调用当前中的js函数"
font.family: "微软雅黑"
onClicked: {
console.log(add(12,13))
helloJs()
}
}
2.调用js文件中的js函数
2.1新建一个js文件,编写函数
2.2导入js文件,注意as后面可以命名为自己喜欢的,类似命名空间
import "test.js" as Test
2.3调用
Button{
id:btn_2
text: "调用js文件中的js函数"
font.family: "微软雅黑"
onClicked: {
var sum = Test.func1(52,58)
console.log(sum)
Test.func2()
}
}
三.完整的qml
import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 2.1
import "test.js" as Test
Window{
visible: true
width: 640
height: 480
title: qsTr("QML调用JS举例")
function add(a,b)
{
return a+b
}
function helloJs(){
console.log("Hello QML-JS")
}
// 行布局
Rectangle{
x:0
y:0
id:row_rect
width: parent.width
height: parent.height
border.color: "green"
radius: 15
Row{
spacing: 5 // 设置行与行之间的间距
anchors.centerIn: parent // 相对于父窗口居中
Button{
id:btn_1
text: "调用当前中的js函数"
font.family: "微软雅黑"
onClicked: {
console.log(add(12,13))
helloJs()
}
}
Button{
id:btn_2
text: "调用js文件中的js函数"
font.family: "微软雅黑"
onClicked: {
var sum = Test.func1(52,58)
console.log(sum)
Test.func2()
}
}
}
}
}