如何使用 Qt 运行 windows cmd 命令?

How to run a windows cmd command using Qt?

我必须使用 Qt 运行 以下命令,这将弹出 Git GUI window。

D:\MyWork\Temp\source>git gui

我该怎么做?

我尝试了以下方法,但没有用:

QProcess process;   
process.start("git gui",QStringList() << "D:\MyWork\Temp\source>");

试试这个:

QProcess process;
process.setWorkingDirectory("D:\MyWork\Temp\source");
process.start("git", QStringList() << "gui");

或者如果你想在一行中完成,你可以这样做(这里我们使用startDetached而不是start):

QProcess::startDetached("git", QStringList() << "gui", "D:\MyWork\Temp\source");

在第二种情况下,最好检查 return 代码(如果您的程序不能 运行 外部程序,则显示错误消息)。您也可以将所有参数放在第一个 program 字符串中(即 process.start("git gui"); 也是允许的):

bool res = QProcess::startDetached("git gui", QStringList(), "D:\MyWork\Temp\source");
if (!res) {
  // show error message
}

即使您使用的是 Qt,您仍然可以调用 Windows API。 ShellExecute 会做这个工作

#include <Windows.h>
ShellExecute(NULL, NULL, "git", "gui", NULL, SW_SHOWNORMAL);

如果您的字符集是 Unicode(宽字符),请尝试以下代码

#include <Windows.h>
ShellExecute(NULL, NULL, _T("git"), _T("gui"), NULL, SW_SHOWNORMAL);

您无需担心分隔符,Qt 会为您处理。

QDir Document

You do not need to use this function to build file paths. If you always use "/", Qt will translate your paths to conform to the underlying operating system. If you want to display paths to the user using their operating system's separator use toNativeSeparators().

为了你的 QProcess,试试这个。

QProcess gitProcess;
gitProcess.setWorkingDirectory("D:/MyWork/Temp/source");
gitProcess.setProgram("git"); // hope this is in your PATH
gitProcess.setArguments(QStringList() << "gui");
gitProcess.start();
if (gitProcess.waitForStarted()) {
  // Now your app is running.
}

我使用以下简单代码段解决了我的问题

#include <QDir>

QDir::setCurrent("D:/MyWork/Temp/source");
system("git gui");

不使用 system() 而是这样做,这样您就可以留在 QT 框架内:

QDir::setCurrent("D:/MyWork/Temp/source");
myProcess.startDetached("git gui");

我知道这个 post 现在有点老了,但我知道 Ilya 的回答有什么问题(据我所知)。由于 QProcess 是在本地范围内创建的,因此无论何时调用范围外的进程,都会自动调用析构函数,并在途中终止进程,正如调试消息所暗示的那样:

Destroyed while process ("git") is still running.

解决此问题的一种方法是在堆上实际动态分配 QProcess 的实例。确保在进程完成后释放内存。

QProcess* process = new QProcess;
process->setWorkingDirectory("D:\MyWork\Temp\source");
process->start("git", QStringList() << "gui");

或者等待过程完成,使用

process.waitForFinished (-1);

我希望这对在 post 中寻找正确答案的任何人有所帮助。