QTextEdit

The QTextEdit class provides an editor that lets you edit and display both plain text and rich text.

Let’s use two labels and a text editor to create a simple program that displays the number of words.


Example

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, it displays the number of words below.


Description

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

We used QTextEdit() class to create a text editor.

If you set setAcceptRichText as False, it perceives everything as plain text.

The label below shows the number of words.


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

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


self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)

If you click clear_btn, the clear_text method is called.


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

self.setLayout(vbox)

Using the vertical box layout, place two labels and one text editor vertically.


def text_changed(self):

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

When the text_changed method is called, use the toPlainText() method to save the text in the text variable.

split() changes the words in the string into a list form.

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

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


Results

../_images/4_20_qtextedit_mac.png

Figure 5-20. Counting number of words using QTextEdit.


Prev/Next