QML官方系列教程——Use Case - Integrating JavaScript in QML

附网址:http://qt-project.org/doc/qt-5/qtquick-usecase-integratingjs.html


Use Case - Integrating JavaScript in QML—— 在QML中集成JavaScript代码

JavaScript代码可以很容易被集成到QML中以提供UI逻辑,必要的控制,或是其他益处。


Using JavaScript Expressions for Property Values —— 使用JavaScript表达式表示属性值

JavaScript表达式可以在QML中用作属性绑定。例如:

Item {
    width: Math.random()
    height: width < 100 ? 100 : (width + 50) /  2
}

·

注意到类似Math.random()这样的函数调用,除非它们的参数改变,否则不会被重新评估。因此这里width绑定的Math.random()只会得到一次随机值,而不会被反复评估。但如果宽度在某种情况下被改变,height属性的值由于绑定将被重新计算。


Adding JavaScript Functions in QML —— 在QML中添加JavaScript函数

JavaScript函数可能在QML组件中声明,类似下面的例子。你可以使用组件的id来调用这个方法。

import QtQuick 2.0

Item {
    id: container
    width: 320
    height: 480

    function randomNumber() {
        return Math.random() * 360;
    }

    function getNumber() {
        return container.randomNumber();
    }

    MouseArea {
        anchors.fill: parent
        // This line uses the JS function from the item
        onClicked: rectangle.rotation = container.getNumber();
    }

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

·

Using JavaScript files —— 使用独立的JavaScript文件

JavaScript文件可以被用来为QML文件的抽象逻辑服务,将你的函数放置在一个.js文件中,像下面这样:

// myscript.js
function getRandom(previousValue) {
    return Math.floor(previousValue + Math.random() * 90) % 360;
}

·

然后将这个文件引入到任何需要使用这个函数的.qml文件,像下面这样:

import QtQuick 2.0
import "myscript.js" as Logic

Item {
    width: 320
    height: 480

    Rectangle {
        color: "#272822"
        width: 320
        height: 480
    }

    MouseArea {
        anchors.fill: parent
        // This line uses the JS function from the separate JS file
        onClicked: rectangle.rotation = Logic.getRandom(rectangle.rotation);
    }

    Rectangle {
        id: rectangle
        anchors.centerIn: parent
        width: 160
        height: 160
        color: "green"
        Behavior on rotation { RotationAnimation { direction: RotationAnimation.Clockwise } }
    }

}

·


需要进一步了解QML中所使用的JavaScript引擎,以及与浏览器上JS的区别,请到Using JavaScript Expressions with QML查看完整文档。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值