1
votes

I have a QProcess where i would like to output the response in a label. First off, here is what i have tried:

QProcess *proc = new QProcess();
proc->setProcessChannelMode(QProcess::MergedChannels);
proc->start(cmdLineRequest.toUtf8().constData()); // cmdLineRequest is omitted

if (!proc->waitForFinished()) {
    qDebug() << "Make failed:" << proc->errorString();
    ui->topBarcode->setText(QString(proc->errorString()));
} else {
    qDebug() << "Make output:" << proc->readAll();

    ui->topBarcode->setText(QString(proc->readAll()) + "asdf");
}

proc->readAll() is a QByteArray and setText accepts a QString. From what i've read, i should be able to cast the QByteArray to a QString, howver it does not work. I have also tried to convert proc->readAll() with the QString class

->setText(QString::fromUtf8(proc->readAll())) // not working
->setText(QString::fromLatin1(proc->readAll())) // not working
->setText(QString::fromLocal8Bit(proc->readAll())) // not working
... etc ...

It seems weird, since i'm adding pictures to labels in nearly the same matter using setPixmap(QPixmap::fromImage(image))

Any help appreciated, thank you.

Update:

If i add a QMessageBox before the end of the method that the above block of code belongs to, i can see the text added to the label. However when i close the QMessageBox, the text dissapears. Am i giving an address position to the label with proc->readAll() or how come this behaviour? Thank you.

2
When you state "it does not work", what do you mean? Does it not compile, or are getting different output from what you are expecting? It is perfectly legitimate to create a QString from a byte array with the string constructor: QString(const QByteArray & ba)TheDarkKnight
Sorry if i was unclear. It compiles allright, it's just that the text is not appended to the label.Attaque

2 Answers

3
votes

The problem here is that you're calling proc->readAll twice; the first for the qDebug output and then again for the string which you set on the label.

{
    qDebug() << "Make output:" << proc->readAll();
    ui->topBarcode->setText(QString(proc->readAll()) + "asdf");
}

I expect that as QProcess is a QIODevice, it's returning a buffered byte array. When you read it, it removes that from the buffer.

Therefore, create a temporary string and read the buffer once, before calling qDebug and setting the string to the label: -

{
    QString output = proc->readAll();
    qDebug() << "Make output:" << output;
    ui->topBarcode->setText(output + "asdf");
}
1
votes

You should listen to readyReadStandardOutput() signal and call readAll() when you receive signal.

or you can call

bool waitForReadyRead(int msecs = 30000)

before calling readAll().