QML - 导入外部 JavaScript 文件

QML - Import external JavaScript file

我可以像这样导入 JavaScript 已经是项目树一部分的文件:

import "myFile.js" as MyFile

有什么方法可以为我的项目中尚未包含的外部文件执行此操作,即通过将绝对路径或相对路径传递到我的光盘上的文件吗?

对于一些问题,例如:

Is it possible to do something like [this...]

通常最简单的方法就是尝试一下。

在你的问题中缺少一个重要的细节:

Is the QML file in question in a qrc-file or not?

如果是,那么您需要告诉 QML 它应该在 qrc 之外查看。与图片一样,您可以通过在其前面加上 file:///.

来做到这一点

绝对路径在这里工作得很好。相对比较棘手,因为您需要预测您来自哪个目录。我不能告诉你。

如果 QML 不在 qrc 中,那么在任何情况下您都将在文件系统上指定一个相对路径,所以这里没有问题。你甚至不需要在前面加上 file:///

如果你想让它更偏远一点,从互联网上试试:

import QtQuick 2.5
import QtQuick.Controls 2.0
import 'http://code.qt.io/cgit/qt/qtdeclarative.git/plain/examples/quick/demos/photoviewer/PhotoViewerCore/script/script.js' as Test

ApplicationWindow {
    id: window
    visible: true
    width: 600
    height: 600

    Button {
        text: 'Calculate Scale of an Image: 100x100px for a target size of 200px'
        onClicked: console.log('It is:', Test.calculateScale(100, 100, 200) + '!\nMagical!')
    }
}

为了更动态的导入,您可以创建一个代理脚本,内容不超过以下内容:

// proxyScript.js

function include(path) { Qt.include(path) }

然后你可以像这样在你的 QML 文件中使用它:

import QtQuick 2.0
import QtQuick.Controls 2.0
import 'proxyScript.js' as Script1
import 'proxyScript.js' as Script2

ApplicationWindow {
    Component.onCompleted {
        // Load scripts here
        var path1 = [...] // Build the absolute path of some script to load
        var path2 = [...] // Build the absolute path of another script to load
        Script1.include(path1) // Now you can access the content of the script at path1 via `Script1.functionFromPath1...`
        Script2.include(path2)
    }
    [...]
}

您还可以将多个 .js 文件导入一个 proxyScript。但是,您导入的脚本函数将具有相同的名称 space.

当然你也可以有更多的静态代理脚本,如果你愿意的话:

// staticProxyScript.js

Qt.include('file:/My/Absolute/Path/To/A/Script/That/I/Want/To/Use.js')