我有一个可以运行其他exe文件的应用。一些按钮并连接到可执行文件。当我单击按钮时,开始运行另一个程序...这很好,但仍保持打开主窗口的状态,程序仍在运行。我想让主窗口在另一个程序正在运行时停止运行(或消失),而当我从另一个应用程序退出时,运行(或出现并运行)主进程。我试过了:
void MainWindow::RunSys(QString sh)
{
this->close();
QProcess ps;
if(ps.execute(sh)<0)
{
QMessageBox messageBox;
messageBox.critical(nullptr,"Error",sh + "Error!");
}
this->show();
}
//I call the function this way:
QString sh = settings->value("Run").toString();
connect(pButton, &QToolButton::clicked, [=] { RunSys(sh); });
它正在Linux上运行。打开可执行程序,但是主程序直到在Windows上运行为止。我该怎么办?
我无法再现该错误,我们需要您提供一个完整,最少和可复制的示例来说明该错误。
如果可以帮助您,我根据您的情况编写了以下示例代码:
标题
class MainWindow : public QMainWindow
{
Q_OBJECT
protected:
QPushButton * pb;
public:
MainWindow();
void runShellCmd(const QString & cmd);
};
实施
MainWindow::MainWindow()
{
// Build the main window
resize(600, 400);
pb = new QPushButton("run cmd", this);
this->setCentralWidget(pb);
// Create the command
QString cmd("ping 127.0.0.1 -n 6");
// Connect the signal
connect(pb, &QPushButton::clicked, [=](){runShellCmd(cmd);});
}
void MainWindow::runShellCmd(const QString & cmd)
{
QProcess ps;
this->close();
int exit_code = ps.execute(cmd);
switch(exit_code)
{
// Do what you want with exit code
default:;
}
this->show();
}
主要功能
int main(int argc, char ** argv)
{
QApplication app(argc, argv);
MainWindow w;
w.show();
return app.exec();
}
而且效果很好。
编辑:
我已经知道出了什么问题。您的calc.exe示例使我轻声问了这个问题:)
实际上,QProcess::execute()
一直阻塞直到命令调用返回。在这种情况下,它将在启动后立即返回,而不是在关闭窗口时返回。这样您就能获得预期的行为。
恐怕这样做会更加困难。因为calc.exe是外部程序,所以除非您可以从外部程序读取某种关闭信号,否则您将无法检测到它何时关闭。