Python > GUI Programming with Python > PyQt > Common Widgets
PyQt QLineEdit Example
This code snippet illustrates the usage of the QLineEdit widget in PyQt, a fundamental component for receiving user input. It demonstrates creating a QLineEdit, connecting it to a signal to capture text changes, and displaying the input in a label.
Importing Necessary Modules
This section imports the required PyQt modules. `QApplication` is essential for any PyQt application. `QWidget` serves as the base class for all UI elements. `QLineEdit` is the text input widget. `QVBoxLayout` arranges widgets vertically. `QLabel` displays text. `Qt` is used for enums and constants related to Qt functionalities and `sys` is necessary to create and execute a QApplication.
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt
import sys
Creating the Main Window
This code defines the main application window. `MainWindow` inherits from `QWidget`. The constructor initializes the window title and geometry (position and size). A QLabel to give instructions and a QLineEdit are created. A QVBoxLayout is used to arrange the label and line edit vertically within the window. The `textChanged` signal of the line edit is connected to the `on_text_changed` slot. This signal is emitted whenever the text in the line edit changes.
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt QLineEdit Example")
self.setGeometry(100, 100, 400, 200)
self.label = QLabel("Enter text in the line edit", alignment=Qt.AlignCenter)
self.line_edit = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.line_edit)
self.setLayout(layout)
self.line_edit.textChanged.connect(self.on_text_changed)
Handling Text Changes
The `on_text_changed` function is called whenever the text in the line edit changes. It receives the new text as an argument and updates the label to display the entered text. This demonstrates how to capture and react to user input in real-time.
def on_text_changed(self, text):
self.label.setText(f"You entered: {text}")
Running the Application
This block of code ensures that the application is run only when the script is executed directly (not imported as a module). It creates a `QApplication` instance, instantiates the `MainWindow` class, shows the window, and starts the event loop using `app.exec_()`. `sys.exit()` ensures a clean exit when the application is closed.
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Concepts Behind the Snippet
This snippet demonstrates the interaction between a user input element (`QLineEdit`) and a display element (`QLabel`). It uses the `textChanged` signal to capture changes in the text field and updates the label in response. This highlights the signal and slot mechanism for handling dynamic user input.
Real-Life Use Case
QLineEdit widgets are used extensively in forms, search bars, and data entry fields. They allow users to input text, numbers, or other data, which can then be processed and used by the application.
Best Practices
Interview Tip
Be prepared to discuss the different signals emitted by QLineEdit (e.g., `textChanged`, `editingFinished`, `returnPressed`). Understand how to use validators and input masks to constrain user input. Also, know how to access the entered text using the `text()` method.
When to use them
Use QLineEdit widgets whenever you need to allow users to enter text data into your application. This includes forms, search fields, configuration settings, and any other scenario where user input is required.
Memory Footprint
QLineEdit widgets generally have a moderate memory footprint. The memory usage depends on the length of the entered text and the complexity of any associated validators or input masks. Optimize the use of validators to minimize memory consumption.
Alternatives
Alternatives to QLineEdit include: QTextEdit (for multi-line text input), QSpinBox (for numerical input with increment/decrement buttons), and QComboBox (for selecting from a list of options). The choice depends on the specific type of input required.
Pros
Cons
FAQ
-
How do I set a placeholder text in QLineEdit?
You can set a placeholder text using the `setPlaceholderText()` method: `line_edit.setPlaceholderText("Enter your name")`. -
How do I restrict the input to numbers only?
You can use a QIntValidator to restrict the input to integers: `validator = QIntValidator() line_edit.setValidator(validator)`