QWidget實現了log日志的打印功能,不僅可以在界面顯示,還可以生成打印日志。先來看下效果,源碼放在文章末尾:
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");
這里分別打印綠色正常信息,黃色警告信息和紅色錯誤信息。
想在項目下生成Log日志還需要做如下設置:
(1)在mainwindow主程序目錄下創建config文件夾并把logconfig.properites文件拷貝進去
(2)附加包含目錄添加logplus頭文件目錄
(3)附加庫目錄添加logplus的lib目錄
(4)附加依賴項添加debug或release的lib文件名
記得更改下logplus.cpp下面的lib路徑
源碼下載
