Checking whether qprocess has finished

巧了我就是萌 提交于 2020-05-18 12:04:49

问题


I have to check whether my process has finished and I need to convert it to bool because I want to you if.
In MainWindow.h I have created an object

QProcess *action;

In 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:


You should connect to the process's finished signal. Your code will get invoked whenever the process finishes. 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();
}


来源:https://stackoverflow.com/questions/38232236/checking-whether-qprocess-has-finished

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!