Use QT to realize regular expression search and narrow it into the system hosting taskbar

Results as shown below:

The red one is the software I implemented zoomed into the system hosting bar 

A regular expression is a powerful tool for matching and manipulating text. It is a pattern consisting of a series of characters and special characters that describe text patterns to be matched. Regular expressions can find, replace, extract and validate specific patterns in text.

1. Use QT to implement regular expressions,

There are mainly the following methods for implementing regular expressions in Qt:

  • Use the QRegExp class, a class for working with regular expressions that provides methods and properties to create, validate, search and replace regular expressions. The QRegExp class supports Perl-style regular expression syntax, and other syntax modes can also be selected. For example, you can use the QRegExp class to verify that an email address is valid:

        The code part is as follows:

// 创建一个正则表达式对象,匹配邮箱地址的格式
QRegExp rx("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
// 创建一个邮箱地址字符串
QString email = "[email protected]";
// 使用exactMatch()方法判断字符串是否完全符合正则表达式
bool valid = rx.exactMatch(email); // 返回true
  • Use the QRegularExpression class, which is a class for processing regular expressions, which was introduced in Qt5 and implemented based on the PcRE library, which is more powerful and flexible than the QRegExp class 2. The QRegularExpression class supports ECMAScript-style regular expression syntax, and other syntax modes can also be selected3. For example, you can use the QRegularExpression class to find all words in a string and count their occurrences:
  • The code part is as follows:
// 创建一个正则表达式对象,匹配单词边界和字母数字字符
QRegularExpression re("\\b\\w+\\b");
// 创建一个字符串
QString text = "Hello, world! This is a test.";
// 使用globalMatch()方法返回一个匹配迭代器
QRegularExpressionMatchIterator i = re.globalMatch(text);
// 创建一个哈希表,用于存储单词和出现次数
QHash<QString, int> wordCount;
// 遍历匹配结果
while (i.hasNext()) {
    // 获取当前匹配对象
    QRegularExpressionMatch match = i.next();
    // 获取匹配到的单词
    QString word = match.captured(0);
    // 将单词转换为小写
    word = word.toLower();
    // 在哈希表中增加单词出现的次数
    wordCount[word]++;
}

Here I choose the second one for demonstration:

Be careful to include the header file #include <QRegExpValidator>, otherwise an error will be reported.

// 调用match()方法,传入一个要匹配的字符串
        ui->textEdit->clear();
        QString need = ui->lineEdit->text();
        // 创建一个QRegularExpression对象,表示匹配一个整数的模式
        QRegularExpression re(need);
        for(const QString file : message)
        {
            QString p=file;
            QRegularExpressionMatch match = re.match(p);
            bool hasMatch = match.hasMatch(); // true
            if (hasMatch)//如果符合正则表达式,那么就输出该文件名
            {
                // 输出该行
                qDebug() << p;
                ui->textEdit->append(p);
            }
            else{
                qDebug()<<"没有匹配";
                qDebug()<<need;
            }
            if(need=="")
            {

                ui->textEdit->append(p);
            }
        }

The above code part mainly obtains the regular expression entered by the user through QlineEdit (for example: .*[specified character].* means any character field containing the specified character) and then uses QRegularExpression to define the regular expression execution that comes with QT. function, QRegularExpressionMatch is the string segment you need to match, bool hasMatch = match.hasMatch(); defines a Boolean value, if the match is successful, it will return a true, which is convenient for us to judge.

2. Use QT to shrink the software to the system hosting bar.

The implementation code is as follows: the header file #include <QSystemTrayIcon> needs to be included, otherwise an error will be reported

 // 创建一个系统托盘图标
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/Acrylic.png")); // 设置图标
    trayIcon->setToolTip("最小化到托盘"); // 设置提示文本
    trayIcon->show();
//     创建一个QMenu对象
    QMenu *trayMenu = new QMenu(this);
//     添加菜单项
    trayMenu->addAction("Show", this, SLOT(show()));
    trayMenu->addAction("Hide", this, SLOT(hide()));
    trayMenu->addSeparator();
    trayMenu->addAction("Exit", qApp, SLOT(quit()));
//     设置系统托盘图标的菜单
    trayIcon->setContextMenu(trayMenu);
//     连接系统托盘图标的activated()信号到自定义的槽函数
    connect(trayIcon, &QSystemTrayIcon::activated, this, &log_device::iconActivated);
//    this->show();

The code in the slot function isconActivated() function in connect is shown in the figure below:

 switch (reason) {
       case QSystemTrayIcon::Trigger: // 单击左键
           // 切换主窗口的可见性
           setVisible(!isVisible());
           break;
       case QSystemTrayIcon::DoubleClick: // 双击左键
           // 显示主窗口,并激活它
           show();
           activateWindow();
           break;
       case QSystemTrayIcon::MiddleClick: // 单击中键
           // 在系统托盘中显示消息
           trayIcon->showMessage("Message", "This is a message from tray icon");
           break;
       default:
           break;
       }

A brief overview of the above function implementation: first create a QSystemTrayIcon object, and then set the icon that is shrunk to the icon in the task management bar for display, and then set the prompt message setToolTip that appears when the mouse moves to the software icon ("you The prompt information you want to show!").

3. Realize the double-click trigger event of Listview

On the UI interface, drag out the listview, select the transfer slot, and then select clicked(QModellndex). Then, write the function you want to achieve under the on_listView_doubleClicked(const QModelIndex &index) function.

void log_device::on_listView_doubleClicked(const QModelIndex &index)
{
    QString trans=index.data().toString();
    qDebug()<<"成功"<<trans;
    QString send_text_path=path+"/"+trans;
    filter=new text_filter;
    filter->show();
    this->hide();
    filter->text_show(send_text_path);
    connect(filter,SIGNAL(open_main_window()), this, SLOT(rebulid_main()));
}

For example, I am here to achieve a double-click popup, another sub-window is instantiated, and when the sub-window is clicked to close, the main window will be displayed again without the program terminating.

Combined with the QTimer in the previous blog, here we can implement a particularly meaningful function. We can use QTime and QFileDialog to manage the logs of our daily system, including quick viewing of logs, and regular deletion and management of logs (To avoid too many logs, resulting in too much computer storage space), the specific implementation design functions are as follows:

First initialize the interface and make a judgment. The judgment function is: the difference in days between the earliest log file and the current time. (So ​​it is strongly recommended to name the log file _20230708_ to indicate the date the log was generated.) The best way to compare the date size is to directly calculate the number of days, year * 365 days + month * 30 + date, and then directly compare the difference .

Then, since we need to process the logs under this folder regularly, we need to set a timer so that the software will execute the above-described judgment every 24 hours in the background. How to implement software background management, we only need to create a new sub-thread for QTimer timing. The purpose of using sub-threads is to avoid blocking the main thread, which will hinder our next log viewing function.

The last is to implement the function of viewing logs. I joined the listview to display all the files under the current folder directory, and then double-clicked to trigger the sub-window, display the text in the sub-window, and set the input field for the user to enter regular expressions to achieve, filter Some unimportant log information, so as to quickly browse to the log information we want. (When implementing this function, I made the listview part non-editable by the way to avoid unnecessary troubles, and also optimized the logic, such as closing the sub-window will return to the display of the main window, while the sub-window is displaying During the process, the main window is directly hidden, and the software icon hidden in the task management bar is added, and three right-click options [hide, show, exit])

The above is my software design experience.

Guess you like

Origin blog.csdn.net/Helloorld_1/article/details/132146359