PyQt5中的QTextBrowser是一个可以显示富文本格式的文本框,它支持在文本框中添加文本、链接、图片等元素。要在QTextBrowser中添加文本,可以使用QTextBrowser的append方法或insertPlainText方法。
from PyQt5.QtWidgets import QTextBrowser, QApplication
app = QApplication([])
text_browser = QTextBrowser()
# 添加文本
text_browser.append('Hello World!')
insertPlainText方法:在指定位置插入文本
from PyQt5.QtWidgets import QTextBrowser, QApplication
app = QApplication([])
text_browser = QTextBrowser()
# 在光标处插入文本
text_browser.moveCursor(QTextCursor.End)
text_browser.insertPlainText('Hello World!')
注意,如果要在文本框中添加富文本格式的内容,可以使用QTextCursor和QTextCharFormat等类来控制文本的格式和样式。
示例代码:
from PyQt5.QtWidgets import QTextBrowser, QApplication
from PyQt5.QtGui import QTextCursor, QTextCharFormat
app = QApplication([])
text_browser = QTextBrowser()
# 添加富文本格式的文本
cursor = text_browser.textCursor()
text_format = QTextCharFormat()
text_format.setFontWeight(QFont.Bold)
text_format.setForeground(Qt.red)
cursor.insertText('Hello', text_format)
cursor.insertText('World!')
希望这些代码对您有所帮助!