【问题标题】:QMessage while waiting for a ping command response等待 ping 命令响应时的 QMessage
【发布时间】:2012-03-29 07:11:42
【问题描述】:

我正在对一个 IP 地址执行 ping 操作,并且我想在 QMessageBox 中显示正在执行 ping 操作。之后,如果收到响应或发生一秒超时,我想关闭 QMessageBox。

代码:

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);
}

我的猜测是我可能需要使用线程来完成这项任务,但由于我是 Qt 新手,问题可能出在其他任何地方。

编辑: 正如@atamanroman 建议的那样,我尝试使用 QProcess,如 Qt 参考中所述,使用 signal void QProcess::finished (int exitCode, QProcess::ExitStatus exitStatus) [signal]:

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();

而且它不起作用。 myBox 永远不会关闭。怎么了?

【问题讨论】:

    标签: c++ qt ping qmessagebox


    【解决方案1】:

    您应该使用QProcess(启动 ping.exe 并解析输出)或QTcpSocket(自己执行 ping)而不是 system(),因为它们是 Qt 的一部分,并且可以在 ping 完成时向您发出信号。连接到该信号以隐藏您的QMessageBox

    【讨论】:

    • 消息框(或者更好的是 QProgressDialog)应该是类成员,而不是在堆栈上本地创建并在插槽 QProcess::finished() 和 ::error() 中关闭连接到。
    【解决方案2】:

    在您的编辑中: 第一:

    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;
    

    我们取出第一个 &

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

    秒: 使用 Linux ping 永远不会停止,那么您将永远不会收到完成的信号。您可以提供 ping 一些参数,例如计数或等待时间。或者启动一个计时器来停止这个过程。

    第三: 您需要匹配信号和插槽之间的参数以避免警告等。 我建议您创建一个本地 SLOT“processfinished(int, QProcess::ExitStatus)”,然后调用 myBox.Close(),但“myBox”必须来自类才能在结束调用的方法后引用它它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2015-12-05
      • 2022-01-04
      • 2022-01-25
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多