背景:
我正在使用 Qt 的 qInstallMsgHandler()
和 qDebug()
,这是一个 GUI 应用程序。
我的消息处理程序与 Qt 的 qtglobal::qInstallMsgHandler()
documentation here 中给出的示例消息处理程序相同。 .
Linux 与 Windows:
在 Linux 上,每次调用 qDebug()
时,消息都会立即显示到控制台......这是很好的且符合预期。
在 Windows 上,每次调用 qDebug()
时,消息都不会显示在控制台上。相反,控制台中什么也没有显示。然后,当应用程序关闭时,所有消息都会突然显示在控制台中。
问题:
如何修复 Windows 上的 Qt 控制台输出(使用 qInstallMsgHandler()
和 qDebug()
)?
最佳答案
在 Windows 上,消息处理程序需要在 fprintf()
之后执行 fflush(stderr)
。 不确定为什么需要这个额外的操作fflush()
但它有效。
长话短说:
我碰巧注意到,在调用 qInstallMsgHandler() 之前,qDebug() 消息实际上在每次调用 qDebug() 之后立即出现。
凭直觉,我决定研究一下 qDebug() 函数。我碰巧在 Windows 上从源代码构建了 Qt,因此我进入了 qDebug() 源代码,发现如果没有消息处理程序,那么它们有一个默认的消息处理程序简短的代码片段。这段代码的基本内容如下:
if (handler) {
(*handler)(msgType, buf);
} else {
fprintf(stderr, "%s\n", buf);
fflush(stderr);
}
我将 fflush(stderr)
添加到我的消息处理程序中,现在 qDebug() 消息确实会出现。
Qt 文档中有关 qDebug() 的警告:
Under Windows, the message is sent to the console, if [your application] is a console application; otherwise [if your application is a GUI application], [your message] is sent to the debugger. This function does nothing if QT_NO_DEBUG_OUTPUT was defined during compilation.
(注:重点是我添加的。方括号中的文字是我自己的。)
关于c++ - 如何修复 Windows 上的 Qt 控制台输出(使用 `qInstallMsgHandler` 和 `qDebug` )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14141104/