zl程序教程

您现在的位置是:首页 >  工具

当前栏目

启用已废弃或过时的Qt方法

Qt方法 启用 过时 废弃
2023-06-13 09:17:28 时间

❝将Qt 4.x过渡到Qt 5.x,或Qt 5.x过渡到最新Qt版本,编译出超多的错误。本文介绍如何降低过渡到高版本带来的维护问题。

注意: 不提倡这种做法,仅供参考。

  我们在使用新版的QtCreator自动生成pro文件中,有这么一段代码。实际上也没有开启。意思是「禁用所有Qt 6.0.0之前的API」

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

用法

  这个宏每次自动创建pro文件都有QT_DISABLE_DEPRECATED_BEFORE,就看看它有什么用吧。下列是Qt官方文档介绍。

This macro can be defined in the project file to 
disable functions deprecated in a specified version of Qt or any earlier version. 
The default version number is 5.0, 
meaning that functions deprecated in or before Qt 5.0 will not be included.

Examples: 
When using a future release of Qt 5, 
set QT_DISABLE_DEPRECATED_BEFORE=0x050100 to disable functions deprecated in Qt 5.1 and earlier. 
In any release, set QT_DISABLE_DEPRECATED_BEFORE=0x000000 to enable any functions, 
including the ones deprecated in Qt 5.0

  大概意思就是:「定义QT_DISABLE_DEPRECATED_BEFORE宏的值可以禁用具体某个版本之前已废弃或过时的方法。」 比如:

# 禁用Qt 5.1版本之前已废弃或过时的方法,
# 这意味着可以使用Qt 5.1版本之后已废弃或过时的方法。
QT_DISABLE_DEPRECATED_BEFORE=0x050100 
# 这个宏更夸张,能使用Qt 5.0版本之前已废弃或过时的方法。
QT_DISABLE_DEPRECATED_BEFORE=0x000000

使用

  1. pro项目文件添加以下代码:
DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x000000
  1. 这样我们就可以使用Qt 5.0版本之前已废弃或过时的方法了。
  2. 例如QAbstractItemModel类的reset()方法。
  3. QAbstractItemModel.h节选源码:
#if QT_DEPRECATED_SINCE(5,0)
    QT_DEPRECATED void reset()
    {
        beginResetModel();
        endResetModel();
    }
#endif