搜索
您的当前位置:首页PyQt5QTextBrowser刷新、上限、查找

PyQt5QTextBrowser刷新、上限、查找

来源:飒榕旅游知识分享网
PyQt5QTextBrowser刷新、上限、查找

使⽤PyQt5做UI,我⼀直使⽤QTextBrowser作为LOG的输出界⾯。不知道对不对。感觉QTextBrowser是⽂本浏览器,就像txt⼀样是查看⽂本的。字⾯意思吧,好吧,我英⽂不好

QTextBrowser刷新

上代码

def text_browser_show(self, mes):

save_str = r\"[{}]◆{}\".format(datetime.now().strftime('%H:%M:%S.%f')[:-3], mes) with open(LogName, 'a') as src_f: print(save_str, file=src_f)

self.textBrowser.append(save_str)

my_cursor = self.textBrowser.textCursor() self.textBrowser.moveCursor(my_cursor.End) # sleep(0.05) # 0:00:01.156

QtWidgets.QApplication.processEvents(QtCore.QEventLoop.AllEvents)解析

with open(LogName, 'a') as src_f: print(save_str, file=src_f)

这个代码是⽤于向⽂件中写log的,本意是在想浏览器输出log的同时也将log写⼊⽂件中,如果不需要可忽略

self.textBrowser.append(save_str)

这段代码就是将mes添加到浏览器中,但是需注意浏览器的光标位置。append()属于QTextEdit槽函数(也不知道为什么QTextBrowser可以调⽤QTextEdit的槽函数,有可能他们都继承⾄PySide2.QtWidgets.QWidget)

append(text)

参数类型:text - str注意:

The new paragraph appended will have the same character format and block format as the current paragraph, determined by the position ofthe cursor.

将带有⽂本的新段落追加到⽂本编辑的末尾

光标影响append()的插⼊位置,所以我们加⼊⽂本后需要将光标移动到指定位置,这⾥移动到⽂末(第⼀次没有⽂本,所以不需要移动)。

my_cursor = self.textBrowser.textCursor()

获取光标

self.textBrowser.moveCursor(my_cursor.End)

移动光标。

textCursor()

返回类型:

PySide2.QtGui.QTextCursor

返回表⽰当前可见光标的QTextCursor的副本。请注意,对返回的游标所做的更改不会影响QTextEdit的游标;使⽤setTextCursor()更新可见光标。

moveCursor(operation[,mode=QTextCursor.MoveAnchor])

参数类型:

operation - MoveOperationmode - MoveMode

通过执⾏给定的操作来移动光标。如果mode为KeepAnchor,则光标将选择其移动的⽂本。这与⽤户按住Shift键并使⽤光标键移动光标时获得的效果相同。

这些都为QTextEdit的函数。所以我觉的应该⽤QTextEdit,然后设置readonly就可以了。不过⾛来了就记录下。

# sleep(0.05) # 0:00:01.156

QtWidgets.QApplication.processEvents(QtCore.QEventLoop.AllEvents)

sleep亲测有时需要有时不需要。可能跟添加⽂本长度有关。保险起见应添加上,不过值可设⼩⼀点。

processEvents([flags=QEventLoop.AllEvents])

参数类型:

flags - ProcessEventsFlagsmaxtime - int注意:

Unlike the processEvents() overload, this function also processes events that are posted while the function runs.

此函数将重载processEvents()。为调⽤线程处理等待的事件数毫秒(毫秒)或直到没有更多要处理的事件(以时间较短者为准)。您可以在程序忙于执⾏长操作(例如,复制⼀个⽂件)。调⽤此函数仅处理调⽤线程的事件。

设置QTextBrowser显⽰上限

browser_document = self.textBrowser.document()browser_document.setMaximumBlockCount(100000)

document()

返回类型:

PySide2.QtGui.QTextDocument注意:

The editor does not take ownership of the document unless it is the document's parent object. The parent object of the provided documentremains the owner of the object. If the previously assigned document is a child of the editor then it will be deleted.此属性保存⽂本编辑器的基础⽂档。

setMaximumBlockCount(maximum)

参数类型:maximum - int

此属性指定⽂档中的块数限制。指定⽂档可能具有的最⼤块数。如果在⽂档中还有更多⽤此属性指定的块,则从⽂档开头删除这些块。负值或零值表⽰该⽂档可以包含⽆限数量的块,默认值为0。属性将限制⽴即应⽤于⽂档内容。设置此属性还会禁⽤撤消重做历史记录。此属性在带有表或框架的⽂档中未定义。可以理解为最⼤⾏数设置

QTextBrowser查找

self.textBrowser.scrollToAnchor('X') # 查询某个关键字(只能将滑轮滚动到第⼀个查到的字符)

scrollToAnchor(name)

参数类型:name - str

滚动⽂本编辑,以便显⽰具有给定名称的锚点;如果名称为空,已经可见或找不到,则不执⾏任何操作。没错,QTextEdit函数

因篇幅问题不能全部显示,请点此查看更多更全内容

Top