PyQt QTextEdit

QTextEdit

The QTextEdit class provides an editor for editing and displaying both plain text and rich text. Let's create a simple program that displays word numbers using two labels and one text editor.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QTextEdit, QVBoxLayout

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.lbl1 = QLabel('Enter your sentence:')
        self.te = QTextEdit()
        self.te.setAcceptRichText(False)
        self.lbl2 = QLabel('The number of words is 0')

        self.te.textChanged.connect(self.text_changed)

        vbox = QVBoxLayout()
        vbox.addWidget(self.lbl1)
        vbox.addWidget(self.te)
        vbox.addWidget(self.lbl2)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QTextEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def text_changed(self):
        text = self.te.toPlainText()
        self.lbl2.setText('The number of words is ' + str(len(text.split())))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

When you type text in a text editor, display the number of words below.

pyqt qtextedit

Related course: Create Desktop Apps with Python PyQt5

Description

self.lbl1 = QLabel('Enter your sentence:')
self.te = QTextEdit()
self.te.setAcceptRichText(False)
self.lbl2 = QLabel('The number of words is 0')

I created a text editor using the QTextEdit() class.

If setAcceptRichText is false, it is all recognized as plain text. The label below displays the word number.

self.te.textChanged.connect(self.text_changed)

Whenever text in a text editor is modified, text_changed method is called.

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.te)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)

Using a vertical box layout, place two labels and one text editor in a vertical direction.

def text_changed(self):
    text = self.te.toPlainText()
    self.lbl2.setText('The number of words is ' + str(len(text.split())))

text_changed method is called, the text in the text editor (self.te) is stored in the text variable using the toPlainText() method.

split() converts words in a string into a list.

len (text.split()) is the number of words in text.

Use setText() to display the word number on the second label.

Related course: Create Desktop Apps with Python PyQt5