导入JavaScript时如何在QML中使用绝对路径?

How to use absolute paths in QML when importing JavaScript?

我无法确定 QML 如何让您在导入 Component 和 JavaScript 文件时使用绝对路径。

据我所知,导入的唯一方法是使用相对路径或将 Components 作为模块导入。

但是由于我无法将 JavaScript 函数作为模块(我可以吗?),我只能做相对路径。

所以我的 headers 在我的大部分组件中都充满了这样的代码:

import QtQuick 2.5
import QtQuick.Layouts 1.2
import MyCompany.Gui 1.0

import "markets"
import "../../../../../../javascript/markets/MarketHelper.js" as MarketHelper

我怎样才能让 JavaScript 像导入 QML 模块一样好?

您可以使用以下 formatJavaScript 文件定义为 qmldir 文件的一部分:

<ResourceIdentifier> <InitialVersion> <File>

Declares a JavaScript file to be made available by the module. The resource will be made available via the specified identifier with the specified version number.

Zero or more JavaScript resource declarations may exist in the qmldir file, however each JavaScript resource must have a unique identifier within any particular version of the module. Example:

MyScript 1.0 MyScript.js

因此,如果您已经有一个 qmldir,您可以向其中添加以下行:

MarketHelper 1.0 MarketHelper.js

那么,你可以这样使用它:

import Market 1.0

// ...    

    Text {
        text: MarketHelper.priceOfOil()
    }

// ...

Qt Quick Controls does this for calendar-related functionality, for example, with CalendarUtils.js.

更多信息: