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:

// Create a regular expression object to match the format of the email address
QRegExp rx("^\w + ([- + .]\w + )*@\w + ([-.]\w + )*\.\w + ([-.]\ \w + )*$");
// Create an email address string
QString email = "[email protected]";
// Use the exactMatch() method to determine whether the string fully matches the regular expression
bool valid = rx.exactMatch(email); // return 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:
// Create a regular expression object that matches word boundaries and alphanumeric characters
QRegularExpression re("\b\w + \b");
// create a string
QString text = "Hello, world! This is a test.";
// Use the globalMatch() method to return a match iterator
QRegularExpressionMatchIterator i = re.globalMatch(text);
// Create a hash table to store words and occurrences
QHash<QString, int> wordCount;
// loop through matching results
while (i. hasNext()) {
    // Get the current matching object
    QRegularExpressionMatch match = i. next();
    // get the matching word
    QString word = match. captured(0);
    // convert word to lowercase
    word = word.toLower();
    // Increment the number of occurrences of the word in the hash table
    wordCount[word] + + ;
}

Here I choose the second one for demonstration:

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

// Call the match() method, passing in a string to match
        ui->textEdit->clear();
        QString need = ui->lineEdit->text();
        // Create a QRegularExpression object that represents a pattern that matches an integer
        QRegularExpression re(need);
        for(const QString file : message)
        {
            QString p=file;
            QRegularExpressionMatch match = re.match(p);
            bool hasMatch = match.hasMatch(); // true
            if (hasMatch)//If it matches the regular expression, then output the file name
            {
                // output the line
                qDebug() << p;
                ui->textEdit->append(p);
            }
            else {
                qDebug()<<"No match";
                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 needs to be included, otherwise an error will be reported

 // create a system tray icon
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/Acrylic.png")); // set icon
    trayIcon->setToolTip("Minimize to the tray"); // Set the prompt text
    trayIcon->show();
// Create a QMenu object
    QMenu *trayMenu = new QMenu(this);
// add menu item
    trayMenu->addAction("Show", this, SLOT(show()));
    trayMenu->addAction("Hide", this, SLOT(hide()));
    trayMenu->addSeparator();
    trayMenu->addAction("Exit", qApp, SLOT(quit()));
// Set the menu for the system tray icon
    trayIcon->setContextMenu(trayMenu);
// Connect the activated() signal of the system tray icon to the custom slot function
    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: // Click the left button
           // toggle the visibility of the main window
           setVisible(!isVisible());
           break;
       case QSystemTrayIcon::DoubleClick: // Double click the left button
           // show the main window and activate it
           show();
           activateWindow();
           break;
       case QSystemTrayIcon::MiddleClick: // Click the middle button
           // display message in system tray
           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 under the on_listView_doubleClicked(const QModelIndex & amp;index) function, the function you want to achieve.

void log_device::on_listView_doubleClicked(const QModelIndex & amp;index)
{
    QString trans=index.data().toString();
    qDebug()<<"success"<<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 as _20230708_ to indicate the date when 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 compare the difference directly .

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.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge