Question

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.

Was it helpful?

Solution

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");
}

OTHER TIPS

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top