对文件内容特殊关键字做高亮处理

效果:

        对文件中指定的关键字(内容)做标记,适用于日志系统特殊化处理。比如对出现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>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/804392.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python爬虫基础快速入门

目录 前言一、什么是爬虫二、快速编写一个爬虫2.1 爬虫需要用到的库2.2 搭建项目工程2.3 安装三方库2.4 案例编写 三、爬虫实战3.1 目标分析3.2 清洗数据 四、代码改进 前言 本博客旨在分享爬虫技术相关知识&#xff0c;仅供学习和研究之用。使用者在阅读本博客的内容时&#…

Qt/C++推流组件使用说明

2.1 网络推流 公众号&#xff1a;Qt实战&#xff0c;各种开源作品、经验整理、项目实战技巧&#xff0c;专注Qt/C软件开发&#xff0c;视频监控、物联网、工业控制、嵌入式软件、国产化系统应用软件开发。 公众号&#xff1a;Qt入门和进阶&#xff0c;专门介绍Qt/C相关知识点学…

镗床工作台开槽的作用

镗床工作台开槽的作用主要有以下几点&#xff1a; 改善工作台的刚度和稳定性&#xff1a;开槽可以增加工作台的刚度&#xff0c;使其能够承受更大的切削力和振动力&#xff0c;提高工作台的稳定性。 方便工件夹紧和定位&#xff1a;开槽可用于夹紧和定位工件&#xff0c;使其能…

ChatGPT利器:让论文写作更高效更精准

ChatGPT无限次数:点击直达 ChatGPT利器&#xff1a;让论文写作更高效更精准 引言 在当今信息爆炸的时代&#xff0c;论文写作是许多学者和专业人士必不可少的任务。然而&#xff0c;即使对于有经验的专业人士&#xff0c;写作仍然是一个繁琐且耗时的过程。在这样的背景下&…

【DM8】序列

创建序列 图形化界面创建 DDL CREATE SEQUENCE "TEST"."S1" INCREMENT BY 1 START WITH 1 MAXVALUE 100 MINVALUE 1;参数&#xff1a; INCREMENT BY < 增量值 >| START WITH < 初值 >| MAXVALUE < 最大值 >| MINVALUE < 最小值…

PostgreSQL入门到实战-第十弹

PostgreSQL入门到实战 PostgreSQL数据过滤(三)官网地址PostgreSQL概述PostgreSQL中OR操作理论PostgreSQL中OR实操更新计划 PostgreSQL数据过滤(三) 了解PostgreSQL OR逻辑运算符以及如何使用它来组合多个布尔表达式。 官网地址 声明: 由于操作系统, 版本更新等原因, 文章所列…

MQ之————如何保证消息的可靠性

MQ之保证消息的可靠性 1.消费端消息可靠性保证&#xff1a; 1.1 消息确认&#xff08;Acknowledgements&#xff09;&#xff1a; 消费者在接收到消息后&#xff0c;默认情况下RabbitMQ会自动确认消息&#xff08;autoAcktrue&#xff09;。为保证消息可靠性&#xff0c;可以…

Thingsboard PE智慧运维仪表板实例(二)【智慧排口截污实例】

ThingsBoard 的仪表板是一个用于可视化和监控物联网数据的重要组件。 它具有以下特点: 1. 可定制性:用户可以根据自己的需求创建各种类型的图表、表格和指标。 2. 数据可视化:以直观的方式展示设备数据,帮助用户快速了解系统状态。 3. 实时更新:实时反映设备的最新数据…

springboot websocket 持续打印 pod 日志

springboot 整合 websocket 和 连接 k8s 集群的方式参考历史 Java 专栏文章 修改前端页面<!DOCTYPE html> <html><head><meta charset="utf-8"><title>Java后端WebSocket的Tomcat实现</title><script type="text/javasc…

java八股文是什么?

"Java八股文"是一个来自中国程序员圈子的术语&#xff0c;用来指代那些在Java编程语面试中常被问到的基础知识点、理论概念和技术细节。这个词源于中国古代科举考试中的“八股文”&#xff0c;指的是一种固定格式和套路的文章。在现代编程面试中&#xff0c;"Ja…

Vant DropdownMenu 下拉菜单带搜索功能

Vant DropdownMenu 下拉菜单带搜索功能 效果图&#xff1a; 上代码&#xff1a; <van-dropdown-menu active-color"#E33737"><van-dropdown-item ref"dropdownItem"><template #title><span>{{ dropdownItem.text }}</span…

【LeetCode热题100】【二叉树】二叉树的直径

题目链接&#xff1a;543. 二叉树的直径 - 力扣&#xff08;LeetCode&#xff09; 要找两个节点之间最多的边数&#xff0c;这个最多的边数必定是某个节点的左右子树的深度之和&#xff0c;因此递归计算每个子树的深度&#xff0c;过程中记录最大和即可 class Solution { pub…

轻松上手,使用Go语言操作Redis数据库

在 Go 语言中使用 Redis 非常简单&#xff0c;可以使用第三方的 Redis 客户端库来与 Redis 服务器进行交互。在 Go 中&#xff0c;一些常用的 Redis 客户端库包括 "github.com/go-redis/redis/v8"、"github.com/gomodule/redigo/redis" 等。 Go 操作 Redi…

PVE下安装配置openwrt和ikuai

开端 openwrt 和 ikuai 是比较出名的软路由系统。我最早接触软路由还是因为我的一个学长要改自己家里的网络&#xff0c;使用软路由去控制网络。我听说后便来了兴致&#xff0c;也在我家搞了一套软路由系统。现在我已经做完了&#xff0c;就想着写个文章记录一下。 软路由简介…

Centos7 部署Zabbix6.0 LTS

官网&#xff1a;Download and install Zabbix 为您的平台安装和配置Zabbix a.安装Zabbix存储库 # yum install zabbix-proxy-mysql zabbix-sql-scripts zabbix-selinux-policy # rpm -Uvh https://repo.zabbix.com/zabbix/6.4/rhel/7/x86_64/zabbix-release-6.4-1.el7.no…

java操作linux

文章目录 远程连接服务器执行linux命令或shell脚本介绍Process的方法相关类UML 工具类基本工具类依赖第三方的工具类 远程连接服务器 java程序远程linux服务器有两个框架分别是&#xff1a;jsch与ganymed-ssh2框架。推荐使用jsch框架&#xff0c;因为ganymed-ssh2框架不支持麒…

IDEA 宝贝插件

1. Codota— 代码智能提示 Codota还包含一个网站&#xff1a;https://www.codota.com/code 2.Alibaba Java Code Guidelines— 阿里巴巴 Java 代码规范 3. SequenceDiagram —— 调用链路自动生成时序图 4. google-java-format —— 代码自动格式化

百度驾驶证C++离线SDK V1.1 C#接入

百度驾驶证C离线SDK V1.1 C#接入 目录 说明 效果 项目 代码 下载 说明 自己根据SDK封装了动态库&#xff0c;然后C#调用。 SDK包结构 效果 项目 代码 using Newtonsoft.Json; using OpenCvSharp; using System; using System.Collections.Generic; using System.D…

C++矩阵库Armadillo出现warning solve() system is singular错误的解决

本文介绍使用C 语言的矩阵库Armadillo时&#xff0c;出现报错system is singular; attempting approx solution的解决方法。 在之前的文章中&#xff0c;我们介绍过Armadillo矩阵库在Visual Studio软件C环境中的配置方法&#xff08;https://blog.csdn.net/zhebushibiaoshifu/a…

使用midjourney搞出一套三国人物画像!

当下已进入如火如荼的全民AI时代&#xff0c;最近体验了下midjourney&#xff0c;使用它的以图生图功能生成出来一套三国人物画像&#xff0c;和大家分享下使用心得。 使用midjourney的准备工作 下载工具 使用midjourney生产图片依赖的工具和流程&#xff0c;大致如下&#…