检查qprocess是否已完成

时间:2016-07-06 19:27:29

标签: c++ qt qprocess

我必须检查我的过程是否已经完成,我需要将其转换为bool,因为我想要你 在MainWindow.h中,我创建了一个对象

QProcess *action;

在mainwindow.cpp

void MainWindow:: shutdown()
{
action=new QProcess(this);
action->start("shutdown -s -t 600");
//and now I want to use if
if (action has finished)
{
  QMessageBox msgBox;
  msgBox.setText("Your computer will shutdown in 1 minute.");
  msgBox.exec();
}

1 个答案:

答案 0 :(得分:1)

您应该连接到进程的finished信号。只要进程完成,您的代码就会被调用。 E.g。

// https://github.com/KubaO/stackoverflown/tree/master/questions/process-finished-msg-38232236
#include <QtWidgets>

class Window : public QWidget {
   QVBoxLayout m_layout{this};
   QPushButton m_button{tr("Sleep")};
   QMessageBox m_box{QMessageBox::Information,
            tr("Wakey-wakey"),
            tr("A process is done sleeping."),
            QMessageBox::Ok, this};
   QProcess m_process;
public:
   Window() {
      m_layout.addWidget(&m_button);
      m_process.setProgram("sleep");
      m_process.setArguments({"5"});
      connect(&m_button, &QPushButton::clicked, &m_process, [=]{ m_process.start(); });
      connect(&m_process, (void(QProcess::*)(int))&QProcess::finished, [=]{ m_box.show(); });
   }
};

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   Window window;
   window.show();
   return app.exec();
}