使用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 of the 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 - MoveOperation
mode - 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 - ProcessEventsFlags
maxtime - 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 document remains 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函數