首页 > 其他分享 >对文件内容特殊关键字做高亮处理

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

时间:2024-04-09 11:32:08浏览次数:15  
标签:文件 高亮 Qt item auto void 关键字 ui SetDialog

效果:

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

public:
    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 exist
    QString 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 exist

    if(!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>

标签:文件,高亮,Qt,item,auto,void,关键字,ui,SetDialog
From: https://blog.csdn.net/weixin_43935710/article/details/137544163

相关文章

  • SQLite数据库文件格式(十五)
     返回:SQLite—系列文章目录   上一篇:SQLite4.9的虚拟表机制(十四)下一篇:SQLite—系列文章目录   ► 目录本文档描述和定义磁盘上的数据库文件自SQLite以来所有版本使用的格式版本3.0.0(2004-06-18).1. 数据库文件SQLite数据库的完整状态通常是包......
  • 断点续传-视频文件的分块和合并
    目录一,前言二,断点续传三,断点续传流程:四,java代码测试分块和合并视频文件分块: 视频文件合并:五,应用(简单了解)一,前言通常视频文件都比较大,项目中需要满足大文件的上传要求,http协议本身对上传文件大小没有限制,但是客户的网络质量,电脑硬件环境等参差不齐,如果一个大的......
  • SpringBoot集成jasypt,加密yml配置文件
    一、Jasypt简介Jasypt是一个Java简易加密库,用于加密配置文件中的敏感信息,如数据库密码。jasypt库与springboot集成,在实际开发中非常方便。1、JasyptSpringBoot为springboot应用程序中的属性源提供加密支持,出于安全考虑,Springboot配置文件中的敏感信息通常需要对它进......
  • 0day 新视窗新一代物业管理系统RegisterManager存在任意文件上传漏洞
     0x01阅读须知        技术文章仅供参考,此文所提供的信息只为网络安全人员对自己所负责的网站、服务器等(包括但不限于)进行检测或维护参考,未经授权请勿利用文章中的技术资料对任何计算机系统进行入侵操作。利用此文所提供的信息而造成的直接或间接后果和损失,均由使用......
  • 致远OA fileUpload.do接口处存在任意文件上传漏洞
     0x01阅读须知        技术文章仅供参考,此文所提供的信息只为网络安全人员对自己所负责的网站、服务器等(包括但不限于)进行检测或维护参考,未经授权请勿利用文章中的技术资料对任何计算机系统进行入侵操作。利用此文所提供的信息而造成的直接或间接后果和损失,均由使用......
  • 039rsync和inotify实时文件同步
    安装注意把ip换一下#主备机器都安装rsync和inotify-toolssudoapt-get-yinstallrsyncinotify-tools#使用nginx配置文件测试:/tmp#cd/tmp&&cp-rf/usr/local/nginx/conf/nginx_conf#初始同步rsync-avz--delete/tmp/[email protected]:/tmp......
  • DISM(Deployment Image Servicing and Management)工具可以用于修复损坏的 Windows 映像
    DISM(DeploymentImageServicingandManagement)工具可以用于修复损坏的Windows映像文件(通常是WIM或VHD文件),以及损坏的系统文件。DISM工具通常用于修复Windows安装映像或运行中的操作系统。您可以使用DISM工具来扫描和修复损坏的系统文件,方法如下:打开命令提示符:......
  • 如何通过跨网软件,实现网络隔离后的文件安全收发摆渡?
    随着企业数字化转型的逐步深入,企业投入了大量资源进行信息系统建设,信息化程度日益提升。绝大多数企业为了防止内部核心数据泄露,会实施网络隔离,比如内外网隔离,或者在内部网络中又划分出研发网、办公网、生产网等。在专业化分工协作的今天,企业与外部客户、合作伙伴等需进行频繁的数......
  • WebView2 系列之-前端向后端传递文件对象
    背景WebView2中,前端到后端的消息传递,通常是不支持传递对象的。但是我在查阅官方文档时发现了一个例外,那就是方法postMessageWithAdditionalObjects如何传递附加对象webview2中,前端js向后端传递消息通常使用window.chrome.webview.postMessage方法,postMessage的定义如下:......
  • 华为手机 鸿蒙系统 或者安卓系统的百度网盘下载的文件保存在手机什么位置如何查看
    华为手机鸿蒙系统或者安卓系统的百度网盘下载的文件保存在手机什么位置如何查看 连接电脑后一般在这里位置计算机\Mate20Pro(UD)\内部存储\Download\BaiduNetdisk也就是用usb(数据线,不是充电线,要四心的)连接手机后,打开手机盘,download目录 ......