我真的很喜欢这种调试能力。在我最近从事的几个项目中,我已经这样做过几次了。这是相关的代码片段。
在 mainwindow.h 中,在你的MainWindow
类,下public
static QTextEdit * s_textEdit;
在 mainwindow.cpp 中,任何函数之外
QTextEdit * MainWindow::s_textEdit = 0;
在 MainWindow 构造函数中
s_textEdit = new QTextEdit;
// be sure to add the text edit into the GUI somewhere,
// like in a layout or on a tab widget, or in a dock widget
在 main.cpp 中,上面main()
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
if(MainWindow::s_textEdit == 0)
{
QByteArray localMsg = msg.toLocal8Bit();
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
}
}
else
{
switch (type) {
case QtDebugMsg:
case QtWarningMsg:
case QtCriticalMsg:
// redundant check, could be removed, or the
// upper if statement could be removed
if(MainWindow::s_textEdit != 0)
MainWindow::s_textEdit->append(msg);
break;
case QtFatalMsg:
abort();
}
}
}
在 main.cpp 的 main() 内部,初始化之前QApplication
实例。
qInstallMessageHandler(myMessageOutput);
注意:这对于任何单线程应用程序都非常有效。一旦您开始使用qDebug()
在你的 GUI 线程之外,你将会崩溃。然后你需要创建一个QueuedConnection
从任何线程函数(任何不在 GUI 线程上运行的函数)连接到您的实例MainWindow::s_textEdit
,像这样:
QObject::connect(otherThread, SIGNAL(debug(QString)),
s_textEdit, SLOT(append(QString)), Qt::QueuedConnection);
如果你最终使用QDockWidget
并利用QMenu
,您还可以做一些其他很酷的事情。最终结果是一个非常用户友好、易于管理的控制台窗口。
QMenu * menu;
menu = this->menuBar()->addMenu("About");
menu->setObjectName(menu->title());
// later on...
QDockWidget *dock;
dock = new QDockWidget("Console", this);
dock->setObjectName(dock->windowTitle());
dock->setWidget(s_textEdit);
s_textEdit->setReadOnly(true);
this->addDockWidget(Qt::RightDockWidgetArea, dock);
this->findChild<QMenu*>("About")->addAction(dock->toggleViewAction());
希望有帮助。