效果:
对文件中指定的关键字(内容)做标记,适用于日志系统特殊化处理。比如对出现Error字段所在的行进行标红高亮
同时支持对关键字的管理以及关键在属性的设置
下面是对内容高亮:
void MainWindow::displayDecodeResilt(const QString &textPath)
{QFileInfo fileInfo(textPath);auto path = fileInfo.absolutePath();auto name = fileInfo.baseName()+".bin";path = path + "/" + name;LogTextEdit* text = new LogTextEdit(this);int indx = mLogPanel->addTab(text, name);mLogPanel->setTabToolTip(indx, path);mLogPanel->setCurrentWidget(text);text->setProperty("path", textPath);text->setContextMenuPolicy(Qt::NoContextMenu);QFile inputFile(textPath);inputFile.open(QIODevice::ReadOnly);QTextStream in(&inputFile);in.setCodec("UTF-8");text->setText(in.readAll());inputFile.close();auto keywords = ParseWork::Instance().getKeywords();foreach (auto key, keywords.keys()){auto names = key.split("-");filterKeyWord(text, names[1], keywords[key]);}
}void MainWindow::filterKeyWord(LogTextEdit *obj, const QString &key, const QString &color)
{if(!obj) return;QTextDocument *document = obj->document();bool found = false;// undo previous change (if any)//document->undo();if (key.isEmpty()) {QMessageBox::information(this, tr("Empty Search Field"),tr("The search field is empty. ""Please enter a word and click Find."));} else {QTextCursor highlightCursor(document);QTextCursor cursor(document);cursor.beginEditBlock();//! [6]QTextCharFormat plainFormat(highlightCursor.charFormat());QTextCharFormat colorFormat = plainFormat;colorFormat.setForeground(QColor(color));while (!highlightCursor.isNull() && !highlightCursor.atEnd()) {highlightCursor = document->find(key, highlightCursor,QTextDocument::FindWholeWords);if (!highlightCursor.isNull()) {found = true;// highlightCursor.movePosition(QTextCursor::WordRight,// QTextCursor::KeepAnchor);highlightCursor.select(QTextCursor::LineUnderCursor);highlightCursor.mergeCharFormat(colorFormat);}}cursor.endEditBlock(); }
}void MainWindow::updateCurrentPage()
{auto widget = mLogPanel->currentWidget();auto window = qobject_cast<LogTextEdit*>(widget);if(!window)return;window->clear();auto path = window->property("path").toString();QFile inputFile(path);inputFile.open(QIODevice::ReadOnly);QTextStream in(&inputFile);in.setCodec("UTF-8");window->setText(in.readAll());inputFile.close();auto keywords = ParseWork::Instance().getKeywords();foreach (auto key, keywords.keys()){auto names = key.split("-");filterKeyWord(window, names[1], keywords[key]);}
}
下面是对关键字设置:
#ifndef SETDIALOG_H
#define SETDIALOG_H#include <QMap>
#include <QDialog>namespace Ui {
class SetDialog;
}class QListWidgetItem;
class SetDialog : public QDialog
{Q_OBJECTpublic:explicit SetDialog(QWidget *parent = nullptr);~SetDialog();protected:void mousePressEvent(QMouseEvent *event);bool eventFilter(QObject *obj, QEvent *event);private slots:void on_okBtn_clicked();void on_canlBtn_clicked();void on_colBtn_clicked();void on_deleteBtn_clicked();void on_addBtn_clicked();void itemClicked(QListWidgetItem *item);void itemRename(QListWidgetItem *item);private:void init();void loadConfig();private:Ui::SetDialog *ui; QString mEditItemText;QString mCurrentClor;QMap<QString, QString> mWords;
};#endif // SETDIALOG_H
#include "setdialog.h"
#include "ui_setdialog.h"
#include "ItemDelegate.h"
#include "parse/parsework.h"#include <QPair>
#include <QFile>
#include <QDebug>
#include <QKeyEvent>
#include <QMessageBox>
#include <QColorDialog>SetDialog::SetDialog(QWidget *parent) :QDialog(parent),ui(new Ui::SetDialog)
{ui->setupUi(this);init();loadConfig();connect(ui->listWidget, &QListWidget::itemClicked, this, &SetDialog::itemClicked);connect(ui->listWidget, &QListWidget::itemChanged, this, &SetDialog::itemRename);connect(ui->listWidget, &QListWidget::itemDoubleClicked, this, [&](QListWidgetItem* item){ mEditItemText = item->text();});
}SetDialog::~SetDialog()
{delete ui;
}void SetDialog::mousePressEvent(QMouseEvent *event)
{auto item = ui->listWidget->itemAt(event->pos());if(!item) ui->listWidget->setCurrentIndex(QModelIndex());QDialog::mousePressEvent(event);
}bool SetDialog::eventFilter(QObject *obj, QEvent *event)
{ if(ui->word == obj ){if(QEvent::MouseButtonPress == event->type()){ui->listWidget->setCurrentIndex(QModelIndex());}else if(event->type() == QEvent::KeyPress){QKeyEvent *e = static_cast<QKeyEvent*>(event);if(e && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)){on_addBtn_clicked();return true;}}}if(ui->listWidget == obj){if(event->type() == QEvent::KeyPress){QKeyEvent *e = static_cast<QKeyEvent*>(event);if(e && (e->key() == Qt::Key_Delete)){on_deleteBtn_clicked();return true;}}}return QDialog::eventFilter(obj, event);
}void SetDialog::on_okBtn_clicked()
{ParseWork::Instance().setKeywords(mWords);accept();
}void SetDialog::on_canlBtn_clicked()
{reject();
}void SetDialog::on_colBtn_clicked()
{auto col = QColorDialog::getColor();if(!col.isValid())return;QPalette pt;mCurrentClor = col.name(QColor::HexRgb);pt.setColor(ui->label_2->backgroundRole(), mCurrentClor);ui->label_2->setAutoFillBackground(true);ui->label_2->setPalette(pt);auto item = ui->listWidget->currentItem();if(!item) return;item->setData(Qt::TextColorRole, QColor(mCurrentClor));auto indx = item->data(Qt::UserRole+1).toString();mWords[indx] = mCurrentClor;
}void SetDialog::on_deleteBtn_clicked()
{ auto item = ui->listWidget->currentItem();if(nullptr == item)return;mWords.remove(item->data(Qt::UserRole+1).toString());delete item;
}void SetDialog::on_addBtn_clicked()
{auto text = ui->word->text();if(text.isEmpty())return;//check the text wheter existQString number("1");if(!mWords.isEmpty())number = mWords.lastKey().split("-").first();auto index = QString::number(number.toInt()+1) + "-" + text;if(!mWords.contains(index)){mWords[index] = mCurrentClor;QListWidgetItem* item = new QListWidgetItem(text, ui->listWidget);item->setSizeHint(QSize(item->sizeHint().width(), 30));item->setData(Qt::TextColorRole, QColor(mCurrentClor));item->setFlags(item->flags() | Qt::ItemIsEditable);item->setData(Qt::UserRole+1, index);ui->word->clear();}else{QMessageBox::warning(this, tr("Warning"), tr("Word already exist!"));}
}void SetDialog::itemClicked(QListWidgetItem *item)
{if(!item)return;QPalette pt;auto key = item->data(Qt::DisplayRole).toString();auto indx = item->data(Qt::UserRole+1).toString();pt.setColor(ui->label_2->backgroundRole(), mWords[indx]);ui->label_2->setPalette(pt); mCurrentClor = mWords[indx];
}void SetDialog::itemRename(QListWidgetItem *item)
{//check wheter the new name existif(!mEditItemText.isEmpty()){auto indx = item->data(Qt::UserRole+1).toString();QString newIndx = indx.split("-").first();newIndx += "-" + item->text();if(item->text().isEmpty()){ui->listWidget->removeItemWidget(item);mWords.remove(indx);delete item;}else if (mWords.contains(newIndx)){QMessageBox::warning(this, tr("Warning"), tr("The keyword already exists"));QSignalBlocker blocker(ui->listWidget);item->setText(mEditItemText);}else{QSignalBlocker blocker(ui->listWidget);item->setData(Qt::UserRole+1, newIndx);mWords[newIndx] = mWords[indx];mWords.remove(indx);}mEditItemText.clear();}
}void SetDialog::init()
{ ui->word->installEventFilter(this);ui->listWidget->installEventFilter(this);ui->label_2->setAutoFillBackground(true);ui->listWidget->setItemDelegate(new ItemDelegate(this));QPalette pt;pt.setColor(ui->label_2->backgroundRole(), "#504652");ui->label_2->setPalette(pt);ui->listWidget->setToolTip(tr("Double-click to rename the keyword"));ui->label_4->setToolTip(tr("Press <delete> key to delete the select keyword"));ParseWork::Instance().dynamicUpdateStyleSheet(this, ":/qss/src/qss/setting.qss");
}void SetDialog::loadConfig()
{mWords.clear();mWords = ParseWork::Instance().getKeywords();QListWidgetItem* item;foreach (auto key, mWords.keys()){auto names = key.split("-");item = new QListWidgetItem(names[1], ui->listWidget);item->setSizeHint(QSize(item->sizeHint().width(), 30));item->setData(Qt::TextColorRole, QColor(mWords[key]));item->setFlags(item->flags() | Qt::ItemIsEditable);item->setData(Qt::UserRole+1, key);}ui->listWidget->setCurrentIndex(QModelIndex());
}
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>SetDialog</class><widget class="QDialog" name="SetDialog"><property name="geometry"><rect><x>0</x><y>0</y><width>422</width><height>294</height></rect></property><property name="windowTitle"><string>Setting Dialog</string></property><layout class="QHBoxLayout" name="horizontalLayout_5" stretch="0,1"><item><widget class="QListWidget" name="listWidget"><property name="sizeAdjustPolicy"><enum>QAbstractScrollArea::AdjustToContents</enum></property><property name="editTriggers"><set>QAbstractItemView::DoubleClicked</set></property></widget></item><item><layout class="QVBoxLayout" name="verticalLayout_2"><item><layout class="QVBoxLayout" name="verticalLayout"><property name="spacing"><number>10</number></property><item><layout class="QHBoxLayout" name="horizontalLayout_4" stretch="0,1,0"><item><widget class="QLabel" name="label_3"><property name="text"><string>Color</string></property></widget></item><item><widget class="QLabel" name="label_2"><property name="text"><string/></property></widget></item><item><widget class="QPushButton" name="colBtn"><property name="text"><string>SetColor</string></property><property name="autoDefault"><bool>false</bool></property></widget></item></layout></item><item><layout class="QHBoxLayout" name="horizontalLayout_3" stretch="0,1,0"><item><widget class="QLabel" name="label"><property name="text"><string>KeyWord</string></property></widget></item><item><widget class="QLineEdit" name="word"/></item><item><widget class="QPushButton" name="addBtn"><property name="text"><string>Add</string></property></widget></item></layout></item><item><spacer name="verticalSpacer"><property name="orientation"><enum>Qt::Vertical</enum></property><property name="sizeType"><enum>QSizePolicy::Minimum</enum></property><property name="sizeHint" stdset="0"><size><width>20</width><height>10</height></size></property></spacer></item><item><layout class="QHBoxLayout" name="horizontalLayout_2" stretch="1,0,0"><property name="spacing"><number>1</number></property><item><spacer name="horizontalSpacer_2"><property name="orientation"><enum>Qt::Horizontal</enum></property><property name="sizeHint" stdset="0"><size><width>40</width><height>20</height></size></property></spacer></item><item><widget class="QPushButton" name="deleteBtn"><property name="text"><string>Remove Select KeyWord</string></property><property name="autoDefault"><bool>false</bool></property></widget></item><item><widget class="QLabel" name="label_4"><property name="text"><string/></property></widget></item></layout></item></layout></item><item><spacer name="verticalSpacer_2"><property name="orientation"><enum>Qt::Vertical</enum></property><property name="sizeHint" stdset="0"><size><width>20</width><height>40</height></size></property></spacer></item><item><layout class="QHBoxLayout" name="horizontalLayout"><item><spacer name="horizontalSpacer"><property name="orientation"><enum>Qt::Horizontal</enum></property><property name="sizeHint" stdset="0"><size><width>40</width><height>20</height></size></property></spacer></item><item><widget class="QPushButton" name="canlBtn"><property name="text"><string>Cancel</string></property><property name="autoDefault"><bool>false</bool></property><property name="default"><bool>false</bool></property></widget></item><item><widget class="QPushButton" name="okBtn"><property name="text"><string>Save</string></property></widget></item></layout></item></layout></item></layout></widget><resources/><connections/>
</ui>