c++ - 如何修复 Windows 上的 Qt 控制台输出(使用 `qInstallMsgHandler` 和 `qDebug` )?

标签 c++ windows qt debugging console

背景:

我正在使用 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/

相关文章:

Mac/Linux 和 Windows 上的 Ruby GUI 开发

linux - 删除 Maven Pom 中的重复依赖项

wpf - 有没有办法在不同的用户上下文中启动 PowerShell 运行空间?

python - 我应该如何编写时间轴的后端代码

c++ - Qt:槽返回值的含义?

c++ - 在 C++ 中抽象文本解析的库

c++ - QT - QAction::eventFilter:不明确的快捷方式重载

c++ - 进行顺序比较的优雅方式 (C++)

c++ - std::vector 操作在某些系统上速度较慢

c++ - 如何翻译 qmessagebox 中的按钮?