Search code examples
c++qtincludecomponentsqml

Include another QML file from a QML file


There's another question on Stackoverflow about this matter but I don't find the accepted solution possible. So I ask again because the old question is out of attention.

The situation is this way. I have application screens defined by 'main.qml', 'feature1.qml', 'feature2.qml'.

These screens share the same toolbar below title bar. The toolbar has multiple items so copy-paste the QML code is like crazy. This question: QML file include - or one monolithic file (structure QML code)? says it's possible to just use QML file name as component name but I can't get it working.

Any solution? with details pls.


Solution

  • Let's assume you have a file called main.qml and a component in another file called MyCustomText.qml. If both files are in the same directory you can directly load the component like this:

    // in Main.qml
    Rectangle {
      id: root
      MyCustomText {
        text: "This is my custom text element"
      }
    }
    

    If MyCustomText.qml is in another subdirectory MyComponents for example to group all your custom components together, you first need to import the directory before using the component the same way:

    // in Main.qml
    import "MyComponents"
    
    Rectangle {
      id: root
      MyCustomText {
        text: "This is my custom text element"
      }
    }
    

    Another important thing to note is that your QML files should always start with an uppercase letter if you want to be able to use them this way

    Of course your Loader solution works too but this is the easiest way to import QML files in other components.