1

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;
  • setText() sets the complete text - so it's doing what you told it to do. If you want to append the new text you have to retrieve the old one via QTextBrowser::text() – chehrlic Dec 15 '21 at 08:06

1 Answers1

0

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);
Mat
  • 461
  • 4
  • 14