qtqt4qt5qmakeqtgui

How to check the selected version of Qt in a .pro file?


I have multiple versions of Qt installed, and I need to compile my project with all of them.
Using a pro file, I could not find in the documentation how to do a conditional compilation.

Ideally, this is what I would like to do:

QT_VERSION = 5   # this can be 4, set manually

if(QT_VERSION == 5) {
   QT += widgets
}
if(QT_VERSION == 4) {
   QT += gui
}

Naturally, the if() command does not exist in pro files.
Is there a better way to do the same thing?


Solution

  • You can use conditional functions and scopes here:

    QT_VERSION = 5   # this can be 4, set manually
    
    equals(QT_VERSION, 5){
       QT += widgets
    }
    equals(QT_VERSION, 4) {
       QT += gui
    }
    

    However, there are a few things that you need to pay attention to in your original code:

    1. Explicitly defining the Qt version is not necessary, and it can make you get a headache if you forgot to change that in the .pro file. Instead, qmake automatically defines a variable QT_MAJOR_VERSION for you.

    2. Using equals will work in this case. However, as noted below, equals performs a string comparison. However, it is better to use greaterThan and lessThan because your code will automatically stop working when you try to compile it with Qt 6 (somewhere in the future).

    3. Adding gui to the QT is not needed, as it is included by default.

    So, your code should be:

    greaterThan(QT_MAJOR_VERSION, 4) {
        QT += widgets
    }
    

    Here are some undocumented qmake gems: