QML中的JavaScript用法详解

熟悉JavaScript的应该都了解Netscape公司,一代骄子虽然倒下了,却给后人留下了最为珍贵的产品和经验,在互联网发展史上享有举足轻重的地位,这里就不讲故事了,虽然很精彩,从未被磨灭。QML是对JavaScript的扩展,提供了JS主机环境,用法相似,但有些地方与浏览器/服务器端提供的JS主机环境(如Node.js)是不同的,用起来又有一些限制,下面列举一些常用的方法。

1QML文件中的JS表达式

初始化时属性绑定——

// Property.qml

import QtQuick 2.0

Rectangle {
    id: colorButton
    width: 360; height: 360
    color: mouseArea.pressed ? "steelblue" : "lightsteelblue"

    MouseArea {
        id: mouseArea
        anchors.fill: parent
    }
}

使用Qt.binding()完成属性绑定——

// Property2.qml

import QtQuick 2.0

Rectangle {
    id: colorbutton
    width: 360; height: 360
    color: "yellow"

    MouseArea {
        id: mouseArea
        anchors.fill: parent
    }

    Component.onCompleted: {
        color = Qt.binding(function() { return mouseArea.pressed ? "red" : "green" })
    }
}

信号处理中的JS表达式——

// Handler.qml

import QtQuick 2.0

Rectangle {
    id: button
    width: 200; height: 100; color: "lightblue"

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onPressed: label.text = "I am Pressed!"
        onReleased: label.text = "Click Me!"
    }

    Text {
        id: label
        anchors.centerIn: parent
        text: "Press Me!"
    }
}

QML文件中函数的JS表达式——

// InlineFunction.qml

import QtQuick 2.0

Item {
    function factorial(a) {
        a = parseInt(a);
        if (a <= 0)
            return 1;
        else
            return a * factorial(a - 1);
    }

    MouseArea {
        anchors.fill: parent
        onClicked: console.log(factorial(5))
    }
}

JS文件中函数的JS表达式——

// factorial.js

function factorial(a) {
    a = parseInt(a);
    if (a <= 0)
        return 1;
    else
        return a * factorial(a - 1);
}

// ExternalFunction.qml

import QtQuick 2.0
import "factorial.js" as MathFunctions

Item {
    MouseArea {
        anchors.fill: parent
        onClicked: console.log(MathFunctions.factorial(10))
    }
}

使用connect()处理信号——

// Connecting.qml

import QtQuick 2.0
import "script.js" as MyScript

Item {
    id: item
    width: 360; height: 360

    MouseArea {
        id: mouseArea
        anchors.fill: parent
    }

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

// script.js

function jsFunction() {
    console.log("Called JavaScript function!")
}

使用Component.onCompleted附加信号

// Startup.qml

import QtQuick 2.0

Rectangle {
    function startupFunction() {
        console.log("startFunction called")
    }

    Component.onCompleted: startupFunction()
}

2QML文件中的JS资源

用独立的JS文件实现QML逻辑部分——

// MyButton.qml

import QtQuick 2.0
import "my_button_impl.js" as Logic

Rectangle {
    id: rect
    width: 360
    height: 360
    color: "red"

    MouseArea {
        id: mousearea
        anchors.fill: parent
        onClicked: Logic.onClicked(rect)
    }
}

// my_button_impl.js

var clickCount = 0;

function onClicked(btn) {
    clickCount += 1;
    if ((clickCount % 5) == 0) {
        btn.color = Qt.rgba(1,0,0,1);
    } else {
        btn.color = Qt.rgba(0,1,0,1);
    }
}

JS文件定义为共享库——

// Calculator.qml

import QtQuick 2.0
import "factorial.js" as FactorialCalculator

Text {
    width: 500
    height: 100
    property int input: 10
    text: "The factorial of " + input + " is: " + FactorialCalculator.factorial(input)
}

// factorial.js

.pragma library

var factorialCount = 0;

function factorial(a) {
    a = parseInt(a);
    if (a > 0)
        return a * factorial(a - 1);
    factorialCount += 1;
    return 1;
}

function factorialCallCount() {
    return factorialCount;
}

使用WorkerScript这个QML类型——

// MyWorkerScript.qml

import QtQuick 2.0

Rectangle {
    width: 300; height: 300

    Text {
        id: myText
        text: 'Click anywhere'
    }

    WorkerScript {
        id: myWorker
        source: "worker_script.js"
        onMessage: myText.text = messageObject.reply
    }

    MouseArea {
        anchors.fill: parent
        onClicked: myWorker.sendMessage({ 'x': mouse.x, 'y': mouse.y })
    }
}

// worker_script.js

WorkerScript.onMessage = function(message) {
    WorkerScript.sendMessage({ 'reply': 'Mouse is at ' + message.x + ',' + message.y })
}

3、导入JS文件

JS文件中导入另一个JS文件——

.import “filename.js” as Qualifier

JS文件中导入QML模块——

.import TypeNamespace MajorVersion.MinorVersion as Qualifier

JS文件中使用Qt.include()来导入另一个JS文件——

// Including.qml

import QtQuick 2.0
import "script2.js" as MyScript

Item {
    width: 360; height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            MyScript.showCalculations(10)
            console.log("Call factorial() from QML:", MyScript.factorial(10))
        }
    }
}

// script2.js

Qt.include("factorial2.js")

function showCalculations(value) {
    console.log("Call factorial() from script2.js:", factorial(value));
}

// factorial2.js

function factorial(a) {
    a = parseInt(a);
    if (a <= 0)
        return 1;
    else
        return a * factorial(a - 1);
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。