PyQt5 QPlainTextEdit widget

Posted: , Updated: Category: Computers

Example of a QPlainTextEdit widget using Python 3 and PyQt5.

Includes:

  • Create QPlainTextEdit widget
  • Change its appearance
  • Connect signal to take action when text changes
  • Get text out of the widget
  • Put text into the widget
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QPlainTextEdit

if __name__ == '__main__':
    app = QApplication(sys.argv)

    main_window = QMainWindow()

    # Create text entry box
    text_edit_widget = QPlainTextEdit()

    # Change font, colour of text entry box
    text_edit_widget.setStyleSheet(
        """QPlainTextEdit {background-color: #333;
                           color: #00FF00;
                           text-decoration: underline;
                           font-family: Courier;}""")

    # "Central Widget" expands to fill all available space
    main_window.setCentralWidget(text_edit_widget)

    # Print text to console whenever it changes
    text_edit_widget.textChanged.connect(
        lambda: print(text_edit_widget.document().toPlainText()))

    # Set initial value of text
    text_edit_widget.document().setPlainText("Type text in here")

    main_window.show()

    # Start event loop
    sys.exit(app.exec_())