PyQt QTextBrowser
The QTextBrowser class provides a rich text (rich text) browser that includes hypertext navigation. This class is read-only and can use links in hypertext documents as an extension of QTextEdit.
To use an editable rich text editor, you must use QTextEdit. It also allows QTextEdit to be setReadOnly() to make editing impossible to use a text browser that does not have hypertext navigation.
Related course: Create Desktop Apps with Python PyQt5
QTextBrowser
The demo below shows how to use the QTextBrowser widget in Python PyQt. You can use QLabel to display short rich text.
import sys
from PyQt5.QtWidgets import (QApplication, QWidget
, QLineEdit, QTextBrowser, QPushButton, QVBoxLayout)
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.le = QLineEdit()
self.le.returnPressed.connect(self.append_text)
self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)
self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)
vbox = QVBoxLayout()
vbox.addWidget(self.le, 0)
vbox.addWidget(self.tb, 1)
vbox.addWidget(self.clear_btn, 2)
self.setLayout(vbox)
self.setWindowTitle('QTextBrowser')
self.setGeometry(300, 300, 300, 300)
self.show()
def append_text(self):
text = self.le.text()
self.tb.append(text)
self.le.clear()
def clear_text(self):
self.tb.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The line editor and text browser appear in the window.
Description
self.le = QLineEdit()
self.le.returnPressed.connect(self.append_text)
I created a line finder.
When you press Enter, append_text method is called.
self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)
Using the QTextBrowser() class, we created a text browser.
If you set SetAcceptRichText() to True, you can use Rich text.
This is because it is True by default, so you don't need to.
SetOpenExternalLinks() to True to connect to external links.
self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)
clear_btn, the clear_text method is called.
def append_text(self):
text = self.le.text()
self.tb.append(text)
self.le.clear()
append_text method functions to append text (self.le.text()) written to the line finder to the text browser (self.tb).
When text is added to the text browser, the clear method is used to remove the text in the line editer.
def clear_text(self):
self.tb.clear()
clear_text a method is called, it will use the clear method to remove the text that was in the text browser (self.tb).
Plain Text
<b>Bold</b>
<i>Italic</i>
<p style="color: red">Red</p>
<p style="font-size: 20px">20px</p>
<a href="https://www.google.com">Google</a>
Enter the above text in order in the line editer and use the enter key to add it to the text browser.
Related course: Create Desktop Apps with Python PyQt5