zl程序教程

您现在的位置是:首页 >  后端

当前栏目

第37篇 QML中导入定义的JS文件

JS文件导入 定义 37 qml
2023-09-14 09:05:33 时间

1、实例

实现鼠标点击矩形框,矩形框随机变色;

首先定义一个JS资源:

my_color.js

function colorSet(rect) {
    rect.color = Qt.rgba(Math.random(),Math.random(),Math.random(),Math.random())
}

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import "my_color.js" as Mycolor

Window {
    id: root
    visible: true
    width: 640
    height: 480

    Rectangle {
        id: rect
        anchors.centerIn: parent
        width: 200
        height: 200
        color: "red"

        MouseArea {
            id: mouse_click
            anchors.fill: parent
            onClicked: Mycolor.colorSet(rect)
        }
    }
}

在qml中内嵌JS资源,当然也可以直接在qml中直接定义JS函数(针对少量代码下)。

把JavaScript资源导入到QML中去啦,用到:

import "my_color.js" as Mycolor