使用Qt在GUI上按下按钮时启动shell脚本

Ric*_*het 5 c++ linux shell qt qprocess

我有一个shell脚本,当在触摸屏PC(Uubntu Lucid Lynx)上执行时,它会在远程服务器上进行备份.现在,我希望通过在其上运行的GUI应用程序中创建一个小Button来实现自动化.该应用程序使用Qt和C++构建.

到现在为止,我可以使用QFileDialog打开文件夹浏览器并导航到.sh文件,但是可以直接打开定义的.sh文件(即通过定义名称和位置)吗?

有一些提示应该使用QProcess,但我对它的实现感到困惑.提前致谢.

lpa*_*app 7

您可以将其设置为阻塞或非阻塞。这取决于您是要阻止主进程还是以异步模式在后台运行 shell 脚本。

此外,由于您不需要输出,因此您甚至不需要在此处实例化,只需使用静态方法即可。

阻塞代码

#include <QString>
#include <QFileDialog>
#include <QProcess>
#include <QDebug>

...

// Get this file name dynamically with an input GUI element, like QFileDialog
// or hard code the string here.

QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Script"), "/", tr("Script Files (*.sh)"));

if (QProcess::execute(QString("/bin/sh") + fileName) < 0)
    qDebug() << "Failed to run";
Run Code Online (Sandbox Code Playgroud)

非阻塞

#include <QString>
#include <QFileDialog>
#include <QProcess>
#include <QDebug>

...

// Get this file name dynamically with an input GUI element, like QFileDialog
// or hard code the string here.

QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Script"), "/", tr("Script Files (*.sh)"));

// Uniform initialization requires C++11 support, so you would need to put
// this into your project file: CONFIG+=c+11

if (!QProcess::startDetached("/bin/sh", QStringList{fileName}))
    qDebug() << "Failed to run";
Run Code Online (Sandbox Code Playgroud)


Nej*_*jat 5

您可以运行shell或bash将脚本作为参数传递:

QProcess process;
process.startDetached("/bin/sh", QStringList()<< "/Path/to/myScript.sh");
Run Code Online (Sandbox Code Playgroud)