QT交互界面:实现按钮运行脚本程序

一.所需运行的脚本

本篇采用上一篇文章的脚本为运行对象,实现按钮运行脚本

上一篇文章:从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();

四.效果展示

相关推荐
yqcoder6 分钟前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
wuqingshun3141591 小时前
重写equals而不重写hashCode,会出什么问题?
java·开发语言
飞猪~1 小时前
LangChain python 版本 第一集
开发语言·python·langchain
李燚3 小时前
Go 项目怎么组织:DDD 4 层 vs MVC vs 脚本式
开发语言·golang·mvc·ddd·agent框架·eino
2zcode4 小时前
免费开源项目文档:基于MATLAB图像处理的啤酒瓶口缺陷检测系统设计与实现
开发语言·图像处理·matlab
人工智能时代 准备好了吗4 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
LONGZETECH4 小时前
新能源汽车动力电池检测仿真教学系统:C/S 分层架构与数字化实训落地全解析
大数据·c语言·开发语言·人工智能·架构·系统架构·汽车
郝学胜-神的一滴4 小时前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
Metaphor6925 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐65 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构