You can get user input with a QLineEdit widget. In this lesson you’ll make a line edit that changes a labels text when run.

A window can contain one or more QLineEdit widgets. They do not contain a label themselves, for UX purposes you may want to add a label to the QLineEdit to tell the user what to type in the box.

Related Course: Create GUI Apps with Python PyQt5

QLineEdit

Adding an input box

The object oriented code below creates a window with the constructor. An input box or line edit is added to the window, this is called a QLineEdit.

Then it adds a label and a line edit:

1
2
3
4
5
6
self.lineEntry = QLineEdit(self)
self.lineEntry.move(16,16)
self.lineEntry.resize(200,40)

self.qlabel = QLabel(self)
self.qlabel.move(16,64)

You can connect every keypress in the input box (QLineEdit) with a method call.

1
self.lineEntry.textChanged.connect(self.onChanged)

In that method set the labels text and adjust the labels size.

1
2
3
def onChanged(self, text):
self.qlabel.setText(text)
self.qlabel.adjustSize()

pyqt text input qlineedit

Example

Copy and paste the example code below to try it yourself:

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
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton

class Example(QMainWindow):

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

self.lineEntry = QLineEdit(self)
self.lineEntry.move(16,16)
self.lineEntry.resize(200,40)

self.qlabel = QLabel(self)
self.qlabel.move(16,64)

self.lineEntry.textChanged.connect(self.onChanged)

self.setGeometry(50,50,320,200)
self.setWindowTitle("QLineEdit Example")
self.show()

def onChanged(self, text):
self.qlabel.setText(text)
self.qlabel.adjustSize()

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

If you are new to Python PyQt, then I highly recommend this book.

Download Examples