Search code examples
c++qtpingqmessagebox

QMessage while waiting for a ping command response


I'm doing a ping to an IP address, and I want to show into a QMessageBox that a ping operation is going on. After that, if a response is received or one second timeout happens, I want to close the QMessageBox.

Code:

int status;
QByteArray command;
QMessageBox myBox(QMessageBox::Information, QString("Info"), QString("Checking connection"), QMessageBox::NoButton, this);

command.append("ping -w 1 172.22.1.1");
status=system(command);
myBox.setStandardButtons(0);
myBox.exec();
if (0==status){ // Response received
    // Some stuff here...
    myeBox.setVisible(false);
}
else { // Timeout
    // Some other stuff here...
    myBox.setVisible(false);
}

My guess is that I may need to use threads for this task, but since I am a Qt newbie maybe the problem is anywhere else.

EDIT: As @atamanroman suggested I've tried to use QProcess, using signal void QProcess::finished ( int exitCode, QProcess::ExitStatus exitStatus ) [signal] as told in Qt reference:

private:
QProcess *process;
//...

      QMessageBox myBox(QMessageBox::Information, QString("Info"), QString("Checking connection"), QMessageBox::NoButton, this);
    QObject::connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &myBox, SLOT(close()));
    command.append("ping -w 1 172.22.1.1");
    process.start(comdand);
        myBox.setStandardButtons(0);
        myBox.exec();

And it's not working. myBox is never closed. What's wrong?


Solution

  • You should use QProcess (start ping.exe and parse output) or QTcpSocket (do the ping yourself) instead of system() because they are part of Qt and can signal you when the ping has finished. Connect to that signal in order to hide your QMessageBox.