检查 qprocess 是否已完成

Checking whether qprocess has finished

本文关键字:已完成 是否 qprocess 检查      更新时间:2023-10-16

我必须检查我的过程是否完成,我需要将其转换为布尔值,因为我想你如果。
在 MainWindow.h 中,我创建了一个对象

QProcess *action;

在主窗口中.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();
}

您应该连接到进程的finished信号。每当该过程完成时,都会调用您的代码。例如

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