c++ - Qt调用外部Python脚本

标签 c++ qt qt4 qprocess

我正在尝试为我用 Python 编写的命令行工具之一编写 GUI 包装器。
有人建议我应该使用 Qt。

下面是我项目的 .cpp 文件:

#include "v_1.h"
#include "ui_v_1.h"
#include<QtCore/QFile>
#include<QtCore/QTextStream>
#include <QProcess>
#include <QPushButton>
v_1::v_1(QWidget *parent) :
    QMainWindow(parent),ui(new Ui::v_1)
    {
        ui->setupUi(this);
    }
    v_1::~v_1()
    {
        delete ui;
    }

void v_1::on_pushButton_clicked()
{
    QProcess p;
    p.start("python script -arg1 arg1");
    p.waitForFinished(-1);
    QString p_stdout = p.readAllStandardOutput();
    ui->lineEdit->setText(p_stdout);
}

下面是我的项目的头文件:

#ifndef V_1_H
#define V_1_H
#include <QMainWindow>
namespace Ui {
class v_1;
}

class v_1 : public QMainWindow
{
    Q_OBJECT   
public:
    explicit v_1(QWidget *parent = 0);
    ~v_1();

private slots:
    void on_pushButton_clicked();
private:
    Ui::v_1 *ui;
};

#endif // V_1_H

UI 文件只是一个按钮和一个 LineEdit 小部件。

我在点击时为按钮分配了一个插槽。 on_pushButton_clicked() 方法在我调用一些实用程序(例如 lsps)时工作正常,它会将这些命令的输出通过管道传递给 LineEdit 小部件,但是当我尝试调用 Python 脚本时,它没有在 LineEdit 小部件上显示任何内容。

如有任何帮助,我们将不胜感激。

最佳答案

您是否尝试过以下方法:

  1. 确保 python 在您的系统路径中
  2. 按照文档中的说明将参数作为 QStringList 传递
  3. 在测试时将 readAllStandardOutput 更改为 readAll

void v_1::on_pushButton_clicked() 
{
    QProcess p;
    QStringList params;

    params << "script.py -arg1 arg1";
    p.start("python", params);
    p.waitForFinished(-1);
    QString p_stdout = p.readAll();
    ui->lineEdit->setText(p_stdout);
}

关于c++ - Qt调用外部Python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15127047/

相关文章:

c++ - QtAddon SerialPort 从 Qt4 到 Qt5

qt - 删除 QNetworkAccessManager::post 返回的 'QNetworkReply *'

C++:指针和编译器(别名?)优化

c++ - boost c++ unordered_map 使用的是什么哈希函数?

c++ - 无法将整数分配给动态分配的二维数组

c++ - MainWindow 中的 QTableView 和选项卡排序

c++ - 警告从结构的 QList 中删除动态创建的结构

c++ - push_back 导致 sgfault

c++ - Qt Creator 5 - 没有设置调试器

c++ - QTableView 带有适用于所有字段的编辑器