Question

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?

Was it helpful?

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.

OTHER TIPS

In your edit: First:

QProcess *process; // This is a pointer, you don't need to add "&" in connect
                   // You should have called "process = new QProcess" before...
QMessageBox myBox; // This is an object, you need to add the "&" to connect;

We take out the first &

QObject::connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), &myBox, SLOT(close()));

second: Using Linux ping will never stop, then you will never have the finished signal. You can provide ping some parameters like count or time to wait. Or start a timer to stop the process.

third: You need to match the parameters between signals and slots to avoid warnings, etc. I sugest you to create a local SLOT "processfinished(int, QProcess::ExitStatus)" and then you call to myBox.Close(), but "myBox" must be from class to have reference to this after end the method where you call it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top