c++qtqmlqtquick2qt-quick

How to import custom qml components via import <Module>.<Submodule> statements?


Here is my directory structure

Myproject
 |- KmcUI
     |- Controls
          |- MyComponent1.qml
          |- qmldir
          |- impl
              |- InternalComponent.qml
              |- qmldir
     |- Window
          |- MyComponent2.qml
          |- qmldir
     |- MyComponent3.qml
     |- qmldir
 |- main.qml

I have following quesitons:

  1. Should I write 3 qmldir files in ./KmcUI, ./KmcUI/Controls and ./KmcUI/Window, respectively? If so, how to write them?
  2. How to install import path? I've tried add absolute/path/to/Propject/KmcUI to QML_IMPORT_PATH environment variable/.pro file and QQmlEngine::addImportPath(), but none of them worked.

EDIT According to comments, I wrote qmldir for each submodule, and the updated directory is shown above. And the content of each qmldir, for example, in .\KmcUI\Window\qml:

module KmcUI.Window
MyComponent2 1.0 MyComponent2.qml

But still doesn't work. Besides, if I want to use InternalComponent, I cannot even use import KmcUI.Controls.impl in MyComponent1.qml.


Solution

  • I finally found the solution!!! Everyone who is confused by Qt documentation should read my answer.

    You should do the following:

    1. Write qmldir for every sub directory, just like I described in question.
    2. Add all of the qmldirs and .qml files to a .qrc file that located in the outermost directory, in my case, is .\KmcUi. Don't forget to change the default prefix \ to the module name, in my case, is KmcUI.
    3. Create a .pri file, just include the .qrc just created in step 3. This step is optional, the most important is ensuring add .qrc in your .pro.
    4. In your own .pro file, include .pri or .qrc created in step 3 or step 2.
    5. Call engine.addImportPath("qrc:/"). You can also add following line to your .pro file. Then use INSTALL_PATH(engine).
    DEFINES += INSTALL_PATH\\(E\\)=\"E.addImportPath(QStringLiteral(\\\"qrc:/\\\"));\"
    
    1. Import your module in your own qml file!