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.
Practice now: Test your Python skills with interactive challenges
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:
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.
self.lineEntry.textChanged.connect(self.onChanged)
In that method set the labels text and adjust the labels size.
def onChanged(self, text):
self.qlabel.setText(text)
self.qlabel.adjustSize()

Example
Copy and paste the example code below to try it yourself:
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_())
Practice now: Test your Python skills with interactive challenges
Practice now: Test your Python skills with interactive challenges