PySide6 QLineEdit Example

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# The QLineEdit widget is a one-line text editor. 

import sys

from PySide6.QtCore import Slot
from PySide6.QtGui import QRegularExpressionValidator
from PySide6.QtWidgets import (QApplication,
    QWidget, QVBoxLayout, QLineEdit, QLabel)


class Window(QWidget):
    
    def __init__(self):

        super().__init__()
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 1 - Create a line edit widget instance
        
        self.line_edit = QLineEdit()
        validator = QRegularExpressionValidator('^[a-zA-Z]*$')
        self.line_edit.setValidator(validator)
        
        self.label = QLabel()
        
        # 3 - Connect the signals with the slots
        
        self.line_edit.textChanged.connect(self.on_text_changed)
        self.line_edit.editingFinished.connect(self.on_editing_finished)
        self.line_edit.inputRejected.connect(self.on_input_rejected)
        
        layout.addWidget(self.line_edit)
        layout.addWidget(self.label)

    # 2 - Create methods to handle line edit events. 
    
    @Slot()
    def on_text_changed(self):
        self.label.setText(self.line_edit.text())
    
    @Slot()
    def on_editing_finished(self):
        self.label.setText(
            f'Editing finished: {self.line_edit.text()}')
        
    @Slot()
    def on_input_rejected(self):
        self.label.setText('Only alphanumeric characters allowed')


if __name__ == '__main__':

    if not QApplication.instance():
        app = QApplication(sys.argv)
    else:
        app = QApplication.instance()

    main_window = Window()
    main_window.show()

    sys.exit(app.exec())

QLineEdit lets you edit a line of plain text. You can enter, copy(), cut(), paste(), undo(), redo() or selectAll() the text using the standard keyboard shortcuts or the built-in context menu. You can constrain the text content using QValidators or input masks. This example features a QRegularExpressionValidator that allows only alphabetic input. You can turn it into a password input field setting its echoMode property to EchoMode.Password. To use QLineEdit in your application

  1. Create a QLineEdit instance and add it to a layout.

  2. Create the slots to handle QLineEdit signals. The textChanged signal is emitted whenever the line edit text changes. The editingFinished signal is emitted when the Enter key is pressed or the line edit widget loses focus. The inputRejected signal is emitted when the user tries to enter invalid input. In this example all three slots set the label text based on the emitted signal.

  3. Connect the signals with the slot methods using the standard PySide6 notation.