PyQt QTextEdit example
The QTextEdit class is a multi-line text box control that displays multiple lines of text, with multiple vertical scrollbars when the text is outside the control’s display range.
It has several functions:
setPlainText()
toPlainText()
setHtml()
toHtml()
clear()
It can contain one or more lines and each line is split using the newline character \n
.
Book: Create Desktop Apps with Python PyQt5
QTextbox example
The example below shows a multiline textbox. You can click the buttons to change the text.
A textbox can be set with plain text .setPlainText()
or with html setHTML()
.
The code for this program is:
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit,QVBoxLayout,QPushButton
import sys
class TextEditDemo(QWidget):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle("QTextEdit")
self.resize(300,270)
self.textEdit = QTextEdit()
self.btnPress1 = QPushButton("Button 1")
self.btnPress2 = QPushButton("Button 2")
layout = QVBoxLayout()
layout.addWidget(self.textEdit)
layout.addWidget(self.btnPress1)
layout.addWidget(self.btnPress2)
self.setLayout(layout)
self.btnPress1.clicked.connect(self.btnPress1_Clicked)
self.btnPress2.clicked.connect(self.btnPress2_Clicked)
def btnPress1_Clicked(self):
self.textEdit.setPlainText("Hello PyQt5!\nfrom pythonpyqt.com")
def btnPress2_Clicked(self):
self.textEdit.setHtml("<font color='red' size='6'><red>Hello PyQt5!\nHello</font>")
if __name__ == '__main__':
app = QApplication(sys.argv)
win = TextEditDemo()
win.show()
sys.exit(app.exec_())
Code analysis:
Import the QTextEdit from PyQt
from PyQt5.QtWidgets import QApplication,QWidget,QTextEdit,QVBoxLayout,QPushButton
Create the textbox:
self.textEdit = QTextEdit()
Add it to the window:
layout = QVBoxLayout()
layout.addWidget(self.textEdit)
...
self.setLayout(layout)
To set plain text in the QTextEdit:
self.textEdit.setPlainText("Hello PyQt5!\nfrom pythonpyqt.com")
To set html in the QTextEdit:
self.textEdit.setHtml("<font color='red' size='6'><red>Hello PyQt5!\nHello</font>")