我安装了多个版本的Qt,需要使用所有这些版本编译我的项目。
使用.pro文件,我在文档中找不到如何进行条件编译的说明。
理想情况下,我希望能够做到以下内容:
QT_VERSION = 5 # this can be 4, set manually
if(QT_VERSION == 5) {
QT += widgets
}
if(QT_VERSION == 4) {
QT += gui
}
在pro文件中自然不存在if()命令。
有没有更好的方法来完成同样的事情?
我安装了多个版本的Qt,需要使用所有这些版本编译我的项目。
使用.pro文件,我在文档中找不到如何进行条件编译的说明。
理想情况下,我希望能够做到以下内容:
QT_VERSION = 5 # this can be 4, set manually
if(QT_VERSION == 5) {
QT += widgets
}
if(QT_VERSION == 4) {
QT += gui
}
在pro文件中自然不存在if()命令。
有没有更好的方法来完成同样的事情?
您可以在此处使用条件函数和作用域:
QT_VERSION = 5 # this can be 4, set manually
equals(QT_VERSION, 5){
QT += widgets
}
equals(QT_VERSION, 4) {
QT += gui
}
然而,在您的原始代码中有一些需要注意的事项:
明确定义Qt版本是不必要的,如果您忘记在.pro文件中更改它,会让您头痛。相反,qmake会自动为您定义一个变量QT_MAJOR_VERSION
。
在这种情况下使用equals
是可以工作的。但是,如下所述,equals
执行字符串比较。然而,最好使用greaterThan
和lessThan
,因为当您尝试使用Qt 6(将来的某个时候)编译代码时,您的代码将自动停止工作。
不需要将gui
添加到QT
中,因为默认已包含它。
因此,您的代码应该是:
greaterThan(QT_MAJOR_VERSION, 4) {
QT += widgets
}
这里有一些未记录的 qmake
宝石:
defined(func, type)
Returns true if func
is defined; type must be either test
or replace
, to match defineTest
or defineReplace
.
equals(var1, var)
(also works as isEqual
).
Returns true if var1 is equal to var2 (string comparison).
lessThan(var1, var2)`
Returns true if var1
is less than var2
(as an integer).
greaterThan(var1, var2)
Returns true if var1
is greater than var2
(as an integer).
inFile(file, var, val)
Returns true if a variable var
is defined in the specified file. Additionally, it can test to see if it has the requested value.
load(string)
Something of a cross between include()
and CONFIG += [feature]
. load(foo)
will look for a file called "foo.prf" in the standard feature path, and execute its contents immediately. Features that are contained within CONFIG
are executed last, after the ".pro" file has finished processing. Like include()
, it will return true if the file was found.
自Qt 5.10版本开始,提供了versionAtLeast 和 versionAtMost测试函数。
使用示例:
!versionAtLeast(QT_VERSION, 5.11.2):error("Use at least Qt version 5.11.2")
附言:我发布了这个答案,因为简单地搜索“qmake check Qt version”并没有找到这些引用(但是此帖子有)。
翻译后:P.S.:由于简单的谷歌搜索“qmake check Qt版本”没有提供相关参考(但这篇文章有),所以发布了此回答。
你可以像这样在一行中进行检查:
equals(QT_MAJOR_VERSION, 5):!lessThan(QT_MINOR_VERSION, 5) {
QT += bluetooth
} else {
message(Qt $$QT_VERSION Bluetooth not supported.)
}
!lessThan
的意思是大于或等于。
这是一个简单的测试。这是我们在QtSerialPort和Qt框架内的其他模块中一直在做的事情:
lessThan(QT_MAJOR_VERSION, 5) {
...
} else {
...
}
类似且常见的情况包括:
contains(QT_MAJOR_VERSION, 5): ...
或者:
greaterThan(QT_MAJOR_VERSION, 4): ...
这里 你可以找到我们在那里做的另一个QtSerialPort示例。