Include another QML file from a QML file

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.


See Qt documentation about reuseable components.

The imported QML file defines a type whose name is the same as the filename (capitalized, less the .qml suffix). QML calls the type a reuseable component. You use that type name to instantiate an object in the importing QML document (file.)

Its not like a C language include, where the text of the included file is inserted into the including file. Its more like importing the name of a class in Python, and then instantiating an object of that class in the importing file. Or somewhat similar to Javascript, the imported file is creating a prototype object, and the importing file is prototypically inheriting from it. Except note the discussion about the root object and what properties of the component will be visible (because of QML's document scoping.) You won't be able to access everything in the imported file as if it were a C include, a Python import, or a JS inheritance.


Finally I have dug it out from internet. Let's say the to-be-included file is 'mycomponent.qml' in this directory structure (Qt Quick):

projectdir/
  qml/
    projectname/
      main.qml
      mycomponent.qml

The content of 'mycomponent.qml' (for example):

Text {
  text:"Hello, Scooby Doo!";
}

We have to load it this way (in 'main.qml'):

Rectangle {
  ...
  Loader {
    source:"mycomponent.qml";
  }
  ...
}