问题
I'm trying to run an external exe from my Qt app. It's an "autorun application" and it has three buttons: one is suppose to run an external installer which is an .exe app.
I tried:
system("Setup.exe")
It works but it displays terminal when running the installer. I also tried:
QProcess::startDetached("Setup.exe");
and also tried:
QProcess *process = new QProcess(this);
process->start("Setup.exe");
but neither works (nothing happens, there are no logs in the console output as well). Can someone point me what I'm doing wrong or suggest a better solution?
Thanks.
回答1:
Here I try to check all possible problems. This code will start your process or show why it does not want to work.
#include <QtCore/QCoreApplication>
#include <QProcess>
#include <QFileInfo>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString pathToExecutable = "c:\\Apps\\MyApp\\Setup.exe";
// Check the path string was written correctly and Qt can see it
QFileInfo fileInfo(pathToExecutable);
QProcess process;
if (fileInfo.exists())
{
if(fileInfo.isExecutable())
{
QObject::connect(&process, &QProcess::errorOccurred,
&process, [&]()
{
qWarning() << process.errorString();
});
/*
Qt doc:
To set a working directory, call setWorkingDirectory().
By default, processes are run in the current
working directory of the calling process.
*/
QString executableDir = fileInfo.absolutePath();
process.setWorkingDirectory(executableDir);
QString absuluteExecutableFilePath = fileInfo.absoluteFilePath();
/*
Even if QFileInfo see your file, QProcess may not run it,
if the path contains spaces
*/
if (absuluteExecutableFilePath.contains(' '));
{
absuluteExecutableFilePath.prepend("\"").append("\"");
}
// If you need to check errors, use start(), but not startDetached()
process.start(absuluteExecutableFilePath);
}
else
{
qWarning() << "Given file is not executable";
}
}
else
{
qWarning() << "File path does not exist or is set incorrectly";
}
return a.exec();
}
来源:https://stackoverflow.com/questions/60969455/how-to-run-an-external-application-from-qt-program