c++ - 在使用 Qt 制作的 GUI 上按下按钮时启动 shell 脚本

标签 c++ linux qt shell qprocess

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

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

有一些提示应该使用 QProcess,但我对它的实现有点困惑。

最佳答案

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

另外,因为你不需要输出,你甚至不需要在这里实例化,只需要使用静态方法。

Blocking code

#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";

Non-blocking

#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";

关于c++ - 在使用 Qt 制作的 GUI 上按下按钮时启动 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23766173/

相关文章:

C++ 将函数实现对象作为接口(interface)类型传递

c++ - 外部模板 : declaration does not declare anything

linux - 在文件夹上克隆文件夹/突袭?

c++ - QGraphicsView 并不总是更新

c++ - 管理退出程序的转义键

c++ - 字符串流的段错误

python - 自动调整Widget高度

Qt5客户端证书认证

php - 当 PHP 脚本通过/user/bin/php 运行时,Error_log 不起作用

linux - unix - chmod 文件的默认 future 权限