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
# 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.label.setText)
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 signals.
@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__':
app = QApplication(sys.argv)
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 QValidator
s 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
-
Create a
QLineEdit
instance and add it to a layout. -
Create the slots to handle
QLineEdit
signals. ThetextChanged
signal is emitted whenever the line edit text changes. TheeditingFinished
signal is emitted when the Enter key is pressed or the line edit widget loses focus. TheinputRejected
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. -
Connect the signals with the slot methods using the standard PySide6 notation.
Note how we connect the QLineEdit.textChanged
signal directly to QLabel.setText
. We didn’t need to write a custom slot in our code to handle textChanged
. QLabel.setText
is itself a slot and their signatures match: textChanged
emits a string and setText
accepts a string, so we were able to save a few lines of code.