一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

解决方法

1 QTextCursor tc = ui->textRec->textCursor();
2 tc.movePosition(QTextCursor::End);
3 tc.insertText(appendStr);

更好的方法

这个方法参考了QT append()函数的源码。

 1     //获取滚动条位置
 2     bool atEnd = ui->textRec->verticalScrollBar()->value() >= ui->textRec->verticalScrollBar()->maximum();
 3     QTextCharFormat fmt;
 4     fmt.setForeground(color);
 5 
 6     QTextCursor tmp(ui->textRec->document());
 7 
 8     tmp.beginEditBlock();
 9     tmp.movePosition(QTextCursor::End);
10 
11     if (!ui->textRec->document()->isEmpty())
12     {
13         tmp.insertBlock(ui->textRec->textCursor().blockFormat(), ui->textRec->textCursor().charFormat());
14     }else{
15 
16         tmp.setCharFormat(ui->textRec->textCursor().charFormat());
17     }
18 
19     tmp.movePosition(QTextCursor::End);
20     tmp.deletePreviousChar();
21 
22     tmp.insertText(appendStr, fmt);
23 
24     // preserve the char format
25     QTextCharFormat oldCharFormat = ui->textRec->textCursor().charFormat();
26 
27     if (!ui->textRec->textCursor().hasSelection())
28         ui->textRec->textCursor().setCharFormat(oldCharFormat);
29 
30     tmp.endEditBlock();
31     if(atEnd)
32         ui->textRec->verticalScrollBar()->setValue(ui->textRec->verticalScrollBar()->maximum());
posted on 2020-12-10 15:58  一杯清酒邀明月  阅读(3841)  评论(0编辑  收藏  举报