Search code examples
qtqmlqt-creatorimporterrorqtquick2

How do I make my own directory in QT QML?


I'm trying to make a directory of a singleton QML File "All.qml" which I can import anywhere else into my project so that I can access its objects (namely the drawer). I made a qmldir file, in the same folder as the "All.qml", and even add the directory to the .qrc file. The contents of the directory is as follows:

Module App.Drawer

singleton All  1.0 All.qml

But when I type in

import App.Drawer.   1.0

It says "module 'App.Drawer' not installed". I can't find any other way to access that drawer, as the project is huge with multiple folders and directories. Can anyone help me?

Also, this project has C++ integrated with it. I tried going and finding some file where maybe the other directories (there are other custom directories, which were made beforehand) have been installed, but couldn't find any.


Solution

  • You have to make sure that QEngine can find the qmldir file, and it has some specific requirements on where it will look.

    First to make QEngine aware of the qmldir file you have to add an import path:

    engine.addImportPath("qrc:/");
    

    Your path may vary, read on:

    The qmldir file has to placed in the folder structure dictated by module name. In your case it is <rootPath>/App/Drawer/qmldir. The "rootPath" is unknown to me, but let's assume you have the following in your qrc file:

    <RCC>
        <qresource prefix="/ProjectX/App/Drawer">
            <file>Drawer.qml</file>
            <file>qmldir</file>
        </qresource>
    </RCC>
    

    Then "rootPath" is qrc:/ProjectX and the import call becomes:

    engine.addImportPath("qrc:/ProjectX");
    

    Also, the module declaration in qmldir should be the same as the folder structure where the qmldir file is placed. (And I think it should be lowercase)

    module App.Drawer
    
    singleton Drawer 1.0 Drawer.qml
    

    If you want Qt Creator to also find the stuff you can use the QML2_IMPORT_PATH environment variable and set it to the correct folder using the same logic.

    You can also place the files in the <Qt_installation_folder>/qml/App/Drawer but this means every project can use it and you have to keep it up-to-date during development, which might be overdone.


    Edit

    To see if your files are lined up correctly, you can add this debug code:

    QDirIterator it(":", QDirIterator::Subdirectories);
    while (it.hasNext()) {
        qDebug() << it.next();
    }