Include another QML file from a QML file

前端 未结 6 1590
天涯浪人
天涯浪人 2020-12-29 21:53

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.

6条回答
  •  伪装坚强ぢ
    2020-12-29 22:13

    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.

提交回复
热议问题