继上节所讲,Qt可以很容易的将一些日志信息保存到文件中,那么日志信息如何输出到窗口呢?
用过VS或者其他IDE的童鞋对日志输出到窗口应该都很熟悉,开发者可以打开一个输出窗口很清晰的查看一些日志信息。
例如VS,如下:
代码如下:
**********log_browser.cpp**********
#include "log_browser.h"
LogBrowser::LogBrowser(QWidget *parent)
: QWidget(parent)
{
this->resize(400, 300);
is_finished = false;
browser = new QTextBrowser();
start_button = new QPushButton();
clear_button = new QPushButton();
start_button->setText("start");
clear_button->setText("clear");
QHBoxLayout *button_layout = new QHBoxLayout();
button_layout->addStretch();
button_layout->addWidget(start_button);
button_layout->addWidget(clear_button);
button_layout->setSpacing(10);
button_layout->setContentsMargins(0, 0, 10, 10);
QVBoxLayout *main_layout = new QVBoxLayout();
main_layout->addWidget(browser);
main_layout->addLayout(button_layout);
main_layout->setSpacing(10);
main_layout->setContentsMargins(0, 0, 0, 0);
this->setLayout(main_layout);
connect(start_button, &QPushButton::clicked, this, &LogBrowser::start);
connect(clear_button, &QPushButton::clicked, browser, &QTextBrowser::clear);
}
LogBrowser::~LogBrowser()
{
}
void LogBrowser::outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QString message;
switch(type)
{
case QtDebugMsg:
message = QString("Debug:");
break;
case QtWarningMsg:
message = QString("Warning:");
break;
case QtCriticalMsg:
message = QString("Critical:");
break;
case QtFatalMsg:
message = QString("Fatal:");
}
browser->append(message.append(msg));
}
void LogBrowser::start()
{
if(!is_finished)
{
for(int i=0; i<1000000; i++)
{
QCoreApplication::processEvents();
qDebug()<<QString("This is a Qt log browser").append(QString::number(i, 10));
}
is_finished = true;
}
}
void LogBrowser::closeEvent(QCloseEvent *event)
{
QMessageBox::StandardButton answer = QMessageBox::question(
this,
tr("Close Log Browser?"),
tr("Do you really want to close the log browser?"),
QMessageBox::Yes | QMessageBox::No
);
if (answer == QMessageBox::Yes)
event->accept();
else
event->ignore();
}
void LogBrowser::keyPressEvent(QKeyEvent *event)
{
event->ignore();
}
**********main.cpp**********
#include "log_browser.h"
#include
#include
QPointer log_broswer;
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
if(log_broswer)
log_broswer->outputMessage(type, context, msg);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
log_broswer = new LogBrowser();
log_broswer->show();
qInstallMessageHandler(outputMessage);
return a.exec();
}
效果如下:
注:
技术在于交流、沟通,转载请注明出处并保持作品的完整性。
作者:╰☆奋斗ing❤孩子` 原文:http://blog.sina.com.cn/s/blog_a6fb6cc90101guz0.html。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章