GrabBag/AppUtils/UICommon/Src/DetectLogHelper.cpp

133 lines
3.6 KiB
C++
Raw Permalink Normal View History

#include "DetectLogHelper.h"
DetectLogHelper::DetectLogHelper(QListView* listView, QObject *parent)
: QObject(parent)
, m_listView(listView)
, m_logModel(nullptr)
, m_lastLogCount(0)
, m_timestampFormat("hh:mm:ss")
, m_showTimestamp(true)
, m_deduplicationEnabled(true)
{
if (m_listView) {
// 创建并设置 QStringListModel
m_logModel = new QStringListModel(this);
m_listView->setModel(m_logModel);
// 设置 QListView 属性
m_listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_listView->setSelectionMode(QAbstractItemView::NoSelection);
m_listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
}
initConnections();
}
DetectLogHelper::~DetectLogHelper()
{
}
void DetectLogHelper::initConnections()
{
// 连接信号槽,支持跨线程更新
connect(this, &DetectLogHelper::logUpdateRequested,
this, &DetectLogHelper::updateLogInUI,
Qt::QueuedConnection);
connect(this, &DetectLogHelper::logClearRequested,
this, &DetectLogHelper::clearLogInUI,
Qt::QueuedConnection);
}
void DetectLogHelper::appendLog(const QString& message)
{
// 通过信号槽机制确保在UI线程中更新
emit logUpdateRequested(message);
}
void DetectLogHelper::clearLog()
{
// 通过信号槽机制确保在UI线程中清空
emit logClearRequested();
}
void DetectLogHelper::setTimestampFormat(const QString& format)
{
m_timestampFormat = format;
}
void DetectLogHelper::setShowTimestamp(bool show)
{
m_showTimestamp = show;
}
void DetectLogHelper::setDeduplicationEnabled(bool enable)
{
m_deduplicationEnabled = enable;
}
QStringListModel* DetectLogHelper::model() const
{
return m_logModel;
}
void DetectLogHelper::updateLogInUI(const QString& message)
{
if (!m_logModel || !m_listView) return;
// 获取当前数据
QStringList logList = m_logModel->stringList();
// 构建日志条目
QString logEntry;
if (m_deduplicationEnabled && message == m_lastLogMessage && !logList.isEmpty()) {
// 相同消息,增加计数并替换最后一条
m_lastLogCount++;
if (m_showTimestamp) {
QString timestamp = QDateTime::currentDateTime().toString(m_timestampFormat);
logEntry = QString("[%1] %2 (x%3)").arg(timestamp).arg(message).arg(m_lastLogCount);
} else {
logEntry = QString("%1 (x%2)").arg(message).arg(m_lastLogCount);
}
// 替换最后一条
logList[logList.size() - 1] = logEntry;
} else {
// 新消息,重置计数
m_lastLogMessage = message;
m_lastLogCount = 1;
if (m_showTimestamp) {
QString timestamp = QDateTime::currentDateTime().toString(m_timestampFormat);
logEntry = QString("[%1] %2").arg(timestamp).arg(message);
} else {
logEntry = message;
}
// 添加新的日志条目
logList.append(logEntry);
}
// 更新模型
m_logModel->setStringList(logList);
// 自动滚动到最底部
if (!logList.isEmpty()) {
QModelIndex lastIndex = m_logModel->index(logList.size() - 1);
m_listView->scrollTo(lastIndex);
}
}
void DetectLogHelper::clearLogInUI()
{
if (m_logModel) {
m_logModel->setStringList(QStringList());
}
// 重置日志计数器
m_lastLogMessage.clear();
m_lastLogCount = 0;
}