QT(22)-调用python

1.mainwindow.h 中声明成员变量

复制代码
private:
    QProcess *m_pythonProcess; // 声明为指针成员变量

2.mainwindow.cpp 中初始化并连接信号

复制代码
#include "mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    // 1. 实例化 QProcess,并将 this 作为父对象(防止内存泄漏)
    m_pythonProcess = new QProcess(this);

    // 2. 连接信号:当 Python 有标准输出时触发
    connect(m_pythonProcess, &QProcess::readyReadStandardOutput, this, [this]() {
        QByteArray output = m_pythonProcess->readAllStandardOutput();
        qDebug() << "[Python 实时输出]:" << output.trimmed();
    });

    // 3. 连接信号:当 Python 有错误输出时触发
    connect(m_pythonProcess, &QProcess::readyReadStandardError, this, [this]() {
        QByteArray error = m_pythonProcess->readAllStandardError();
        qDebug() << "[Python 报错]:" << error.trimmed();
    });

    // 4. 连接信号:当 Python 进程结束时触发
    connect(m_pythonProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, [this](int exitCode, QProcess::ExitStatus exitStatus) {
        qDebug() << "Python 进程已结束,退出码:" << exitCode;
    });
}

// 假设这是你的按钮点击事件
void MainWindow::on_startButton_clicked() {
    QString pythonPath = "python"; 
    QString scriptPath = "ui/demo/main.py";

    // 启动进程(非阻塞,瞬间返回,界面不会卡!)
    m_pythonProcess->start(pythonPath, QStringList() << scriptPath);
    
    // 如果想等待启动成功,可以用 waitForStarted(),这个很快,不会卡界面
    if (!m_pythonProcess->waitForStarted(3000)) {
        qDebug() << "Python 启动失败!";
    }
}