C++ Qt 执行外部程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19442400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:49:32  来源:igfitidea点击:

Qt Execute external program

c++qtexternal

提问by Testerrrr

I want to start an external program out of my QT-Programm. The only working solution was:

我想从我的 QT-Programm 中启动一个外部程序。唯一可行的解​​决方案是:

system("start explorer.exe");

But it is only working for windows and starts a command line for a moment.

但它仅适用于 Windows 并暂时启动命令行。

Next thing I tried was:

我尝试的下一件事是:

QProcess process;
QString file = QDir::homepath + "file.exe";
process.start(file);
//process.execute(file); //i tried as well

But nothing happened. Any ideas?

但什么也没发生。有任何想法吗?

回答by tomvodi

If your processobject is a variable on the stack (e.g. in a method), the code wouldn't work as expected because the process you've already started will be killed in the destructor of QProcess, when the method finishes.

如果您的process对象是堆栈上的变量(例如在方法中),则代码将不会按预期工作,因为您已经启动的进程将在 的析构函数中QProcess终止,当方法完成时。

void MyClass::myMethod()
{
    QProcess process;
    QString file = QDir::homepath + "file.exe";
    process.start(file);
}

You should instead allocate the QProcessobject on the heap like that:

你应该QProcess像这样在堆上分配对象:

QProcess *process = new QProcess(this);
QString file = QDir::homepath + "/file.exe";
process->start(file);

回答by nv95

If you want your program to wait while the process is executing, you can use

如果您希望您的程序在进程执行时等待,您可以使用

QProcess::execute(file);

instead of

代替

QProcess process;
process.start(file);

回答by nnesterov

QDir::homePath doesn't end with separator. Valid path to your exe

QDir::homePath 不以分隔符结尾。您的 exe 的有效路径

QString file = QDir::homePath + QDir::separator + "file.exe";

回答by Jason C

Just use QProcess::startDetached; it's static and you don't need to worry about waiting for it to finish or allocating things on the heap or anything like that:

只需使用QProcess::startDetached; 它是静态的,您无需担心等待它完成或在堆上分配东西或类似的事情:

QProcess::startDetached(QDir::homepath + "/file.exe");

It's the detached counterpart to QProcess::execute.

它是 的分离对应物QProcess::execute