Qt QTextEdit/QTextBrowser append() 函数换行解决方法
作者:互联网
解决方法
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());
标签:tmp,Qt,QTextBrowser,QTextEdit,textRec,textCursor,ui,verticalScrollBar,QTextCurso 来源: https://www.cnblogs.com/ybqjymy/p/14115554.html