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());


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM