QML-調用JS


一、使用JS文件中的函數

1、新建js文件nomal_fun.js

function getColor(){
    return "red";
}

2、在qml中使用

import QtQuick 2.0
import "nomal_fun.js" as Balls
Rectangle{
    width: 600
    height: 480
    color: "gray"
    Rectangle {
        width: 100
        height: 100
        anchors.centerIn: parent
        Component.onCompleted: {
           color = Balls.getColor()
        }
    }
}

 

 注意:這里並沒有將js文件加入到工程的資源中,而是直接通過文件訪問的。

 

 

二、在js中動態創建自定義qml對象

1、dynamic-image.qml.js

// M1>>
var component;

function createImageObject() {
    component = Qt.createComponent("dynamic-image.qml");
    if (component.status === Component.Ready || component.status === Component.Error) {
        finishCreation();
    } else {
        component.statusChanged.connect(finishCreation);
    }
}

function finishCreation() {
    if (component.status === Component.Ready) {
        var image = component.createObject(root, {"x": 100, "y": 100});
        if (image === null) {
            console.log("Error creating image");
        }
    } else if (component.status === Component.Error) {
        console.log("Error loading component:", component.errorString());
    }
}

// <<M1

dynamic-image.qml是自定義的qml

2、使用

import QtQuick 2.5
import "create-component.js" as ImageCreator

Item {
    id: root

    width: 1024
    height: 600

    Component.onCompleted: ImageCreator.createImageObject();
}

 

三、傳回調進入js

1、在qml里定義函數

function print(info) {
    console.log(info);
}

2、定義js文件

A.js

function test(info, callback)
{
    callback(info);
}

3、qml中使用

import "A.js" as AObject

Item {
    id: root

    function addUfo() {
        AObject.test("123", print);
    }

    function print(info) {
        console.log(info);
    }
}

和C++一致

 

四、stateful/statelss

如希望某個js是單例的,只需要在js文件開頭加入:

.pragma library

注意這種形式類似於共享,它不可以直接訪問QML文件中的object盡管可以通過參數的傳人對所要求的object進行修改;

stateful:【不加.pragma library,默認情況】

如果在js中定義一個var count=0;那么每import一次這個js,就會有獨立的count;默認是有狀態【stateful】的,js文件可以直接訪問在我們QML文件中所定義的object。

statelss:【加.pragma library】

count是靜態的;函數里無法在里面訪問id,只能將id作為參數傳進去才能訪問;

 

官方說明:https://doc.qt.io/qt-5/qtqml-javascript-resources.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM