一.所需运行的脚本
本篇采用上一篇文章的脚本为运行对象,实现按钮运行脚本
上一篇文章:从0到1:QT项目在Linux下生成可以双击运用的程序(采用脚本)-CSDN博客
二.调用脚本的代码
widget.cpp中添加以下代码
#include "widget.h"
#include "./ui_widget.h"
#include <QMessageBox>
#include <QProcess>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton_test, &QPushButton::clicked, this, &Widget::on_pushButton_test_clicked);
}
void Widget::on_pushButton_test_clicked()
{
QString strCmd = "/home/popo/double_click_test/jiao";
QProcess process;
process.start("bash", QStringList() << "-c" << strCmd);
if (process.waitForStarted())
{
qDebug() << "Process started successfully.";
if (process.waitForFinished())
{
QByteArray result = process.readAllStandardOutput(); // 读取脚本的输出
QByteArray error = process.readAllStandardError(); // 读取错误输出
qDebug() << "Script output:" << result;
qDebug() << "Script error output:" << error;
}
else
{
qWarning() << "Failed to execute script";
}
}
else
{
qWarning() << "Failed to start script execution";
}
process.close();
}
三.代码解析
启动进程
process.start("bash", QStringList() << "-c" << strCmd);
检查进程是否成功启动
if (process.waitForStarted())
等待进程执行完成
再次使用 waitForFinished
,等待进程执行完成。如果成功,返回 true
。
进程提示信息
if (process.waitForStarted())
{
qDebug() << "Process started successfully.";
if (process.waitForFinished())
{
QByteArray result = process.readAllStandardOutput(); // 读取脚本的输出
QByteArray error = process.readAllStandardError(); // 读取错误输出
qDebug() << "Script output:" << result;
qDebug() << "Script error output:" << error;
}
else
{
qWarning() << "Failed to execute script";
}
}
else
{
qWarning() << "Failed to start script execution";
}
关闭进程
process.close();