arkhon
arkhon

Reputation: 765

get qprocess output in slot

i have a problem with a small program (I am a beginner with c++ and qt). On button press it starts a cli application with qprocess and the output should be displayed in a text field as soon as the cli app writes it to stdout or stderr.

i read that its a good idea to use signals and slots for this but it isnt working.

the compiler throws an error that in my slot getOutput() the "process" object isn't declared (C2065)

here is the code.

processgui.cpp:

#include "processgui.h"
#include "ui_processgui.h"
#include <QProcess>

processGui::processGui(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::processGui)
{
    ui->setupUi(this);
}

processGui::~processGui()
{
    delete ui;
}

void processGui::on_startProcess_clicked() {

    QProcess *process = new QProcess(this);
    QString program = "tracert";
    QString arguments = "";

    process->setReadChannelMode(QProcess::MergedChannels);

    process->start(program, QStringList() << arguments);

    process->waitForStarted();

    QObject::connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(getOutput()));

}

void processGui::getOutput() {

    QByteArray strdata = process->readAllStandardOutput();

    ui->textLog->append(strdata);

}

processgui.h :

#ifndef PROCESSGUI_H
#define PROCESSGUI_H

#include <QMainWindow>

namespace Ui {
class processGui;
}

class processGui : public QMainWindow
{
    Q_OBJECT

public:
    explicit processGui(QWidget *parent = 0);
    ~processGui();

private slots:
    void on_startProcess_clicked();

    void getOutput();

private:
    Ui::processGui *ui;
};

#endif // PROCESSGUI_H

thanks in advance

Upvotes: 0

Views: 1497

Answers (3)

lena
lena

Reputation: 1191

You can access QProcess object inside a slot with sender(), like this:

void processGui::getOutput() 
{
    QProcess* process = qobject_cast<QProcess*>(sender());
    QByteArray strdata = process->readAllStandardOutput();    
}

Upvotes: 0

ariwez
ariwez

Reputation: 1313

 QProcess *process = new QProcess(this);

is declared in:

void processGui::on_startProcess_clicked() 

it's a scope problem, process is a local variable not available in the whole class.

Upvotes: 1

thuga
thuga

Reputation: 12931

Move QProcess *process to your header and initialize it with process = new QProcess(this) in your constructor. That way you can access it in your slot.

Upvotes: 1

Related Questions