簡體   English   中英

QML-導入外部JavaScript文件

[英]QML - Import external JavaScript file

我可以像這樣導入已經在項目樹中的JavaScript文件:

import "myFile.js" as MyFile

對於我的項目中尚未包含的外部文件,是否可以通過將絕對或相對路徑傳遞到光盤上的文件的方式來執行此操作?

對於一些類似的問題:

是否可以做類似[this ...]的事情

通常最簡單的方法就是嘗試一下。

您的問題中缺少一個重要的細節:

QML文件是否在qrc文件中?

如果是,那么您需要告訴QML,它應該在qrc之外。 與圖片一樣,您可以在其前面加上file:///作為前綴。

絕對路徑在這里可以正常工作。 親戚比較棘手,因為您需要預測來自哪個目錄。 我不能告訴你。

如果QML不在qrc ,則qrc都將在文件系統上指定相對路徑,因此這里沒有問題。 您甚至不需要在file:///加上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 proxyScript 但是,導入的腳本的功能將位於相同的名稱空間中。

當然,如果需要,您還可以具有更多的靜態代理腳本:

// staticProxyScript.js

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM