Pregunta

I get continuous answers from a server with a delay from 1 sec. I append() this answers to an QTextEdit field. But the changes first displayed when the method call has finished. How can I displayed the changes immediately? I have tryed update() but it doesent work..

void ClientWidget::setAnswer(ValueStream *resultStream){

    std::vector<std::string> answer;

    for(int i = 0; i < 15; i++){
        value tmpResultValue;   
        if(resultStream->get(tmpResultValue)){
            this->client.parseResult(tmpResultValue, answer);
            std::vector<QString> qAnswer = vectorStringToVectorQstring(answer);
            for (unsigned int n = 0; n < qAnswer.size(); n++){
                this->answerTextEdit->append(qAnswer[n]);
            }
            this->answerTextEdit->update();
        }
        answer.clear();
    }
    resultStream->close();
    delete resultStream;
}

after this->answerTextEdit->append(qAnswer[n]); the changes should displayed but they dont displayed immediately

¿Fue útil?

Solución

When you set the TextEdit widget's text, a signal is emitted that it has changed, in order for the widget to update what you see. That signal is placed in a queue of messages that are processed as events in the Qt event loop.

While you're processing the incoming data, Qt's event loop cannot continue until you finish. An easy, but not the best way of handling this is to call QApplication::processEvents to allow the event loop to run; this can be very inefficient as all events in the queue are processed.

A better way to handle time-consuming processing is to move it onto a new thread, which is reasonably easy to do with QThread. That way, you can process the incoming requests from the server and emit a signal from your thread to the main thread, which can then update the TextEdit widget.

To understand how to use QThread, I suggest reading this article. It really isn't difficult to do and I recommend you try it, rather than adding a call to QApplication::processEvents.

Otros consejos

You can call

QApplication::processEvents();

after calling your method.

if you can change ValueStream to emit a signal each time a new value is available with the value as a parameter, then it will become much easier. just connect a slot to it where you append the answer to the answerTextEdit

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top