问题
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