gpt4 book ai didi

javascript - QML - 导入外部 JavaScript 文件

转载 作者:行者123 更新时间:2023-11-28 14:48:30 27 4
gpt4 key购买 nike

我可以导入已经是项目树一部分的 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)
}
[...]
}

您还可以在一个 proxyScript 中导入多个 .js 文件。但是,您导入的脚本的函数将位于相同的 namespace 中。

当然,如果您愿意,您还可以拥有更多静态代理脚本:

//staticProxyScript.js

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

关于javascript - QML - 导入外部 JavaScript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45484222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com