13

Like we have preprocessor directives in C++ for conditional includes.

Similarly, how to do conditional importing in QML?

if x  
    import ABC 1.0  
else  
    import PQR 2.0  
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

3 Answers3

9

Depending on what you want to achieve, a possible workaround is to use a Loader. But it does not import a module, it just allows to choose dynamically which QML component you'll use.

Loader
{
    source: condition?"RedRectangle.qml":"BlueRectangle.qml"
}
5

extending a little bit the @Yoann answer:

 Loader
 {
        source: x?"ABC.qml":"PQR.qml"
 }

where ABC.qml :

import ABC 1.0
...

and PQR.qml :

import PQR 2.0  
...

or if don't what to have real qml files you can create them at runtime with:

Loader{
  source:x ? Qt.createQmlObject('import ABC 1.0;',parentItem,"dynamicSnippet1") : Qt.createQmlObject('import PQR 2.0;',parentItem,"dynamicSnippet1")
}
Rui Sebastião
  • 855
  • 1
  • 18
  • 36
0

If you need to find a more dynamic solution for a problem where you were including "hard" imports initially to build your QML component, I recommend checking out:

https://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html

Of note, I just used something like the following to resolve my current use case:

property bool myDynamicSwitch : true
property var myDynamicComponent :( myDynamicSwitch ? Qt.createComponent(
    "qrc:/MyCoolComponent.qml" ) : null )
property var myDynamicObject :( myDynamicComponent ?
    myDynamicComponent.createObject( root ) : null )
BuvinJ
  • 10,221
  • 5
  • 83
  • 96