QWidget实现了log日志的打印功能,不仅可以在界面显示,还可以生成打印日志。先来看下效果,源码放在文章末尾:
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP

LogPlugin插件类管理log所有功能,它可以获取Log界面并能打印正常信息,警告信息和错误信息,下面是它的接口描述:

class LOGGINGWRAPPER_EXPORT LogPlugin
{
public:
    virtual ~LogPlugin() {}

    virtual void Info(std::string message) = 0;   //打印绿色正常信息
    virtual void Warn(std::string message) = 0;   //打印黄色警告信息
    virtual void Error(std::string message) = 0;  //打印红色错误信息

    virtual QWidget* GetLogWidget() = 0;         //获取Log界面
    virtual void SetParent(QWidget* widget) = 0;   //设置父窗口
};

使用方法:

1、创建LogPlugin对象
LogPlugin是QPlugin插件实现,可以通过QPlugin读取LogPlugin.dll,把读到的QObject指针强转为LogPlugin对象。插件的使用可以看之前的篇章。

LogPlugin* logPlugin = qobject_cast<LogPlugin*>(objectPtr);

当然也可以直接new一个LogPlugin对象。

2、把Log界面放在收缩栏中
我把log界面放在了收缩栏中,可以看到鼠标点击log界面可以收起,再次点击可以展开,收缩栏的实现前面文章已经讲解过,这里不在赘述。QWidget实现收缩栏效果

 CollpasePagePlugin* collpasePagePlugin = qobject_cast<CollpasePagePlugin*>(objectPtr_);
 if (logPlugin && collpasePagePlugin)
  {
      collpasePagePlugin->GetWidget()->setParent(ui.centralWidget);
      collpasePagePlugin->SetLayout(m_centerQVBoxLayout, -1); //Put the folded plug-in into the layout
  }

上面代码先创建收缩栏对象,并设置收缩栏的父窗口和垂直布局,-1代表放置在收缩栏中的界面放在布局的最上层位置。

logPlugin->SetParent(collpasePagePlugin->GetWidget()); //Set Parent Class
QWidget* widget = logPlugin->GetLogWidget();

//Put the Logwidget into the folding plug-in
collpasePagePlugin->addWidget(widget, "Log", QIcon(":/Gen2WGMTFTester/images/routine/log.jpg"));

SetParent把log界面的父窗口设为收缩栏,并通过addWidget把Log窗口添加到收缩栏中显示

3、打印log信息

logPlugin->Info("green is normal");
logPlugin->Warn("yellow is warning");
logPlugin->Error("red is error");

这里分别打印绿色正常信息,黄色警告信息和红色错误信息。
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP

想在项目下生成Log日志还需要做如下设置:
(1)在mainwindow主程序目录下创建config文件夹并把logconfig.properites文件拷贝进去
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP

(2)附加包含目录添加logplus头文件目录
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP
(3)附加库目录添加logplus的lib目录
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP
(4)附加依赖项添加debug或release的lib文件名
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP
记得更改下logplus.cpp下面的lib路径
《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP

源码下载

《QT从基础到进阶·三十八》QWidget实现炫酷log日志打印界面-LMLPHP
11-22 15:14