Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to import qml file in another qml file without using relative path



  • Hi All,

    My file structure is :

    C:\Users\Documents\project\source\qml\Common

    Common folder has :
    Toolbar.qml
    Menubutton.qml

    C:\Users\Documents\project\source\qml\Views

    Views folder has:
    Welcomscreen.qml

    So i need to import Toolbar.qml in Welcomscreen.qml right now i am using import "../Common/" which is working but i do not want to use relative path , can any one help me is there any way i can use import "qrc:qml/Common",

    i tried to have alias name that also did not help me.

    Thanks in advance :)


  • Moderators

    As mentioned in chat - I don't know of any built-in solution to this.

    There is one thing that will work - add qmldir file to your Common dir to transform it into a QML module. Then you can import with something like import Common 1.0.

    The big disadvantage of this is that qmldir file has to be maintained and quite frankly it is cumbersome.



  • @sierdzio

    So using relative path would be better?


  • Moderators

    Easier. Whether it's better or not depends highly on specifics of your project. If you move files a lot, then qmldir can be more convenient (no need to update any paths!). If you instead add to Common dir files often, you will have to keep modifying your .qrc file and your qmldir, which is annoying.

    There is no clear answer IMO.



  • @sierdzio

    Thanks for the suggestion



  • @sierdzio

    i have created a qmldir inside Common folder , can you please help me to add this module to access import Common 1.0 in other qml files.

    where i should add this module ?

    Do i need to add qmldir to my qrc file?

    Do i need to engine.addImportPath("qrc:/qml/Common/qmldir"); in main.cpp

    thanks


  • Moderators

    @sush123 said in How to import qml file in another qml file without using relative path:

    @sierdzio

    i have created a qmldir inside Common folder , can you please help me to add this module to access import Common 1.0 in other qml files.

    https://doc.qt.io/qt-5/qtqml-modules-qmldir.html

    Your qmldir should be something like:

    module ModuleName
    singleton SomeSingleTonFile 1.0 SomeSingleTonFile.qml
    SomeOtherFile 1.0 SomeOtherFile.qml
    

    And then in QML:

    import ModuleName 1.0
    // ...
    SomeOtherFile {
      // it works!
    }
    

    where i should add this module ?

    Do i need to add qmldir to my qrc file?

    Yes. Both the dir and all of the files inside need to be in QRC.

    Do i need to engine.addImportPath("qrc:/qml/Common/qmldir"); in main.cpp

    No.



  • thanks for the reply ,

    But i did try the same steps but still i am getting "Qml module not found error".

    sample of qmldir

    module GUI.Source.Qml.Common

    Sample 1.0 Sample.qml


Log in to reply