- QTextBrowser有两种模式, 一种是直接填充文本, 一种是填充html, 针对这两种方式, 更新的方法也不太一样; 不过原理都是一样的
实现原理
QTextBrowser 本身未直接提供更新的方法, 需要通过光标的移动来进行选择并删除, 再通过重新设置值的方式进行更新;
对于文本, 需要 xxxText 相关方法支持
对于html, 需要 xxxHtml/xxxBlock相关的方法支持, html的操作是块级别的
实现方法
对于文本
def update_row(self, msg):
# 获取光标选择器
lastLine = self.textBrowser.textCursor()
# 选中光标所在行
lastLine.select(QtGui.QTextCursor.LineUnderCursor)
# 移除当前行内容
lastLine.removeSelectedText()
# 移动光标到行首
self.textBrowser.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.MoveAnchor)
# 重新设置值
self.textBrowser.insertPlainText(msg)
# textBrowser: QTextBrowser
对于html
def update_row(self, msg):
# 获取光标选择器
cursor = domain.textCursor()
# 选中光标所在块
cursor.select(QTextCursor.BlockUnderCursor)
# 移除当前块
cursor.removeSelectedText()
# 重新设置值
domain.append(msg)
# 移动光标到最后(方便下一次插入, 否则会插入在当次之前)
domain.moveCursor(QTextCursor.End)
# textBrowser: QTextBrowser