qtimportqmlqmakercc

Importing QML Document Directories


I want to import my custom QML type MyType from subdirectory mytypes into my main.qml file. Which is also in the same directory with the mytypes folder. I used this documentation page as reference. http://doc.qt.io/qt-5/qtqml-syntax-directoryimports.html

I use it as follows:

import "mytypes"

MyType {

}

In code, MyType is recognized and highlighted as usual. However, when I run the application, I get the following error:

qrc:/main.qml:5:1:  "mytypes": no such directory

And my .qrc file looks like that:

<RCC>
<qresource prefix="/">
    <file>main.qml</file>
</qresource>
<qresource prefix="/mytypes">
    <file>mytypes/MyType.qml</file>
</qresource>
</RCC>

So where is the error? Should I also make some changes in the .pro file?


Solution

  • The qrc file

    <qresource prefix="/mytypes">
        <file>mytypes/MyType.qml</file>
    </qresource>
    

    says mytypes/MyType.qml is under the prefix /mytypes. Therefore, the import statement in main.qml should include that prefix:

    import "mytypes/mytypes"
    
    MyType { }
    

    Or, remove /mytypes prefix and move mytypes/MyType.qml under / prefix in qrc file:

    <RCC>
        <qresource prefix="/">
            <file>main.qml</file>
            <file>mytypes/MyType.qml</file>
        </qresource>
    </RCC>
    

    and main.qml can import the type directly:

    import "mytypes"
    
    MyType { }