Overwriting the text in slot

Viewed 19

I am designing a chat application. My query is that I am printing the message and name of the user in a chat box on pressing a send button in Qt. Every time I press the button instead of writing the new message in next line, it erases the previous message and overwrites it by showing the new message only.

Code:

QString str = ui->textEdit->toPlainText();
    QString name= ui->textEdit->objectName();
    ui->textBrowser->setText(name);
    ui->textBrowser->setText(name + ": " + str);
    std::cout<<endl;
1 Answers

setText() sets the text in the textEdit (and not appends what you have probably guessed), therefore your second setText() overwrites the first one.

    QString str = ui->textEdit->toPlainText();
    QString name= ui->textEdit->objectName();
    
    QString oldMsg = ui->textBrowser->text();
    QString newMsg = name + ": " + str;

    ui->textBrowser->setText(oldMsg + "\n" + newMsg);
Related