Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
jondinham Avatar asked Mar 04 '14 09:03

jondinham


People also ask

How do I insert one QML file into another?

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.

How do I use a QML file in Qt?

Creating and Running QML Projects For simple UI files such as this one, select File > New File or Project > Application (Qt Quick) > Qt Quick Application - Empty from within Qt Creator. Pressing the green Run button runs the application. You should see the text Hello, World! in the center of a red rectangle.

What is alias in QML?

Using alias means use another name for property like C++ reference type declaration it must been init at time that has been created. The main usage of alias is to ability to export inner scope property to outer scope of object scope. Also we can use property to achieve this goal across binding feature of qml.

What is Qmldir file?

A qmldir file is a plain-text file that contains the following commands: Syntax. Usage. module <ModuleIdentifier> Declares the module identifier of the module.


1 Answers

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.

like image 116
koopajah Avatar answered Sep 22 '22 05:09

koopajah