Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write conditional import statements in QML?

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  
like image 964
Aquarius_Girl Avatar asked Dec 12 '14 09:12

Aquarius_Girl


2 Answers

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"
}
like image 175
Yoann Quenach de Quivillic Avatar answered Oct 23 '22 13:10

Yoann Quenach de Quivillic


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")
}
like image 20
Rui Sebastião Avatar answered Oct 23 '22 13:10

Rui Sebastião