Qt程序在Debug模式下跟踪Q_ASSERT断言

本文介绍了Qt程序中如何处理Debug模式下的Q_ASSERT断言问题,通过全局函数qInstallMsgHandler实现捕获并自定义消息输出,包括调试、警告、关键和致命错误消息的打印控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般情况下,Qt程序在Debug模式下碰到Q_ASSERT断言就会崩溃,无法跟踪到Call Stack进行调试,特别是Q_ASSERT在Qt代码内部,如QVector越界等情况,这让人很头疼。为此,Qt提供了一个全局函数用于捕获这类断言:

Q_CORE_EXPORT QtMsgHandler qInstallMsgHandler(QtMsgHandler);
Qt文档是这样解释的:

QtMsgHandler qInstallMsgHandler ( QtMsgHandler handler )
Installs a Qt message handler which has been defined previously. Returns a pointer to the previous message handler (which may be 0).

The message handler is a function that prints out debug messages, warnings, critical and fatal error messages. The Qt library (debug mode) contains hundreds of warning messages that are printed when internal errors (usually invalid function arguments) occur. Qt built in release mode also contains such warnings unless QT_NO_WARNING_OUTPUT and/or QT_NO_DEBUG_OUTPUT have been set during compilation. If you implement your own message handler, you get total control of these messages.

The default message handler prints the message to the standard output under X11 or to the debugger under Windows. If it is a fatal message, the application aborts immediately.

Only one message handler can be defined, since this is usually done on an application-wide basis to control debug output.

To restore the message handler, call qInstallMsgHandler(0).


调用方式:

 #include <qapplication.h>
 #include <stdio.h>
 #include <stdlib.h>

 void myMessageOutput(QtMsgType type, const char *msg)
 {
     switch (type) {
     case QtDebugMsg:
         fprintf(stderr, "Debug: %s\n", msg);
         break;
     case QtWarningMsg:
         fprintf(stderr, "Warning: %s\n", msg);
         break;
     case QtCriticalMsg:
         fprintf(stderr, "Critical: %s\n", msg);
         break;
     case QtFatalMsg:
         fprintf(stderr, "Fatal: %s\n", msg);
         abort();        // 在这里产生中断
     }
 }

 int main(int argc, char **argv)
 {
     qInstallMsgHandler(myMessageOutput);
     QApplication app(argc, argv);
     ...
     return app.exec();
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值