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
Qt Execute external program
提问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 process
object 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 QProcess
object 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
。