Usage of QOverload in Qt5

In order to illustrate the use of QOverload, we implement the detection of network reachability between hosts, and Ping is a network tool used to detect reachability between hosts

In order to avoid blocking the UI, you can use the asynchronous method of QProcess to execute the Ping command, and get the execution result by connecting the signal of QProcess. This keeps the UI responsive while pinging in the background. Here is sample code:

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

#include <QCoreApplication>
#include <QTimer>
#include <QProcess>
#include <QDebug>

class PingChecker : public QObject
{
    Q_OBJECT

public:
    explicit PingChecker(QObject *parent = nullptr)
        : QObject(parent)
    {
        // 创建定时器并设置定时间隔(单位:毫秒)
        timer = new QTimer(this);
        timer->setInterval(5000);  // 每隔5秒执行一次Ping检测

        // 连接定时器的timeout信号到Ping检测槽函数
        connect(timer, &QTimer::timeout, this, &PingChecker::checkPing);

        // 启动定时器
        timer->start();
    }

private slots:
    void checkPing()
    {
        QString ipAddress = "127.0.0.1";  // 替换为你要Ping的IP地址

        QProcess* pingProcess = new QProcess(this);
        pingProcess->start("ping", QStringList() << "-c" << "1" << ipAddress);  // "-c 1"表示只发送一个Ping请求

        // 连接QProcess的finished信号到处理结果的槽函数
        connect(pingProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
                this, [this, ipAddress](int exitCode, QProcess::ExitStatus exitStatus) {
            QString pingResult = pingProcess->readAllStandardOutput();
            bool isReachable = pingResult.contains("1 packets transmitted, 1 received");

            if (isReachable) {
                qDebug() << "Ping succeeded. IP address" << ipAddress << "is reachable.";
            } else {
                qDebug() << "Ping failed. IP address" << ipAddress << "is not reachable.";
            }

            pingProcess->deleteLater();
        });
    }

private:
    QTimer *timer;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    PingChecker pingChecker;

    return a.exec();
}

In the above code, we use a Lambda expression to connect the finished signal of QProcess to an anonymous slot function. This allows the results to be processed asynchronously after the ping operation is complete, and the QProcess object is released in the slot function. This avoids blocking the UI thread.

Please note that when executing the Ping command in an asynchronous manner, the created QProcess object needs to be released in time to prevent memory leaks. We use pingProcess->deleteLater() in the slot function to delay the release of the QProcess object to ensure that it is released after the slot function is executed.

This way, you can perform ping detection in the background and keep the UI responsive.

// 连接QProcess的finished信号到处理结果的槽函数
        connect(pingProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
                this, [this, ipAddress](int exitCode, QProcess::ExitStatus exitStatus) {
            QString pingResult = pingProcess->readAllStandardOutput();
            bool isReachable = pingResult.contains("1 packets transmitted, 1 received");

In the example, QQverload is used, and a detailed explanation is given below:

When you connect a signal to a slot, Qt provides several different ways of connecting. One way is to use the QOverload template class to specify the parameter type of the slot function.

QOverload is a template class used to solve the problem of overloaded function linkage. Its template parameter is the argument list of the slot function to be linked. In this case, QOverload<int, QProcess::ExitStatus> specifies that the parameters of the slot function are int and QProcess::ExitStatus.

In the QProcess class, there is an overloaded finished signal, which has two parameters: exitCode of type int and exitStatus of type QProcess::ExitStatus. Therefore, when you want to connect to this overloaded signal, you need to use QOverload to specify the parameter type of the slot function so that Qt can correctly match the signal and slot function.

In the above sample code, we used Lambda expressions as slot functions. By using QOverload<int, QProcess::ExitStatus>::of, we tell Qt that we are connecting to an overloaded version of the QProcess::finished signal, which takes two parameters, int and QProcess::ExitStatus.

The advantage of using QOverload is that it provides type safety, ensuring that the parameter types of the connected signals and slots match. The compiler will issue an error if the specified parameter types do not match.

To sum up, QOverload<int, QProcess::ExitStatus>::of is used to specify the parameter type of the slot function to connect to the overloaded version of the QProcess::finished signal, where the int parameter represents the exit code of the process, QProcess::ExitStatus The parameter indicates the exit status of the process.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, C++ design pattern, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project actual combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/131231749