1
votes

I am unable to identify how QML lets you use absolute paths when importing Components and JavaScript files.

As far as I can understand, the only way to import is to either use relative paths or import Components as a module.

But since I cannot make JavaScript functions as modules (or can I?), I can only do relative paths.

So my headers in most of my components are filled with code like this:

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

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

How am I able to let JavaScript be imported as nicely as QML modules?

1

1 Answers

2
votes

You can use the following format to define a JavaScript file as part of a qmldir file:

<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

So, if you already have an existing qmldir, you can add the following line to it:

MarketHelper 1.0 MarketHelper.js

Then, you could use it like this:

import Market 1.0

// ...    

    Text {
        text: MarketHelper.priceOfOil()
    }

// ...

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

For more information: