In my 12+ years of developing desktop applications for clients across the USA, I have found that knowing about input widgets is important to building professional applications. Recently while building a customer relationship management system as a part of my project, I used the QLineEdit widget. In this article, I will explain how to create QLineEdit widget in PyQt6 with examples and screenshots.
Create QLineEdit Widget in PyQt6
QLineEdit is a single-line text input widget in PyQt6 that allows users to enter and edit a single line of plain text. It serves as the digital equivalent of form fields you encounter in paper documents or web forms. While seemingly simple, QLineEdit offers useful features for text validation, formatting, and interaction that make it indispensable for almost every desktop application.
Read How to Create Icons for Windows in PyQt6?
Create Your First QLineEdit
Let’s start creating our first QLineEdit from basics – creating a simple text input field:
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QVBoxLayout
class TextInputApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# Create layout
layout = QVBoxLayout()
# Create label
label = QLabel("Enter your name:")
# Create a basic text input
self.name_input = QLineEdit()
self.name_input.setPlaceholderText("John Smith")
self.name_input.textChanged.connect(self.on_text_changed) # Connect signal
# Add widgets to layout
layout.addWidget(label)
layout.addWidget(self.name_input)
# Set layout and window properties
self.setLayout(layout)
self.setWindowTitle("Basic QLineEdit Example")
self.setGeometry(100, 100, 500, 200)
self.show() # Show the window
def on_text_changed(self, text):
print(f"Current text: {text}") # Print text as it changes
if __name__ == "__main__":
app = QApplication(sys.argv)
window = TextInputApp()
sys.exit(app.exec())I executed the above example code and added the screenshot below.

This creates a simple input field with a placeholder text “John Smith” that will print the current text to the console whenever the text changes.
Check out Types of Windows in PyQt6
Input Validation and Constraints
For most business applications, validating user input is important. QLineEdit offers several methods for input validation and constraints:
Input Masks
Input masks in PyQt6 provide a way to enforce a specific format for user input. They are particularly useful for fields like phone numbers, credit card numbers, dates, and postal codes, ensuring that users enter data in a predefined structure.
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit
class PhoneNumberApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# Create layout
layout = QVBoxLayout()
# Create label
phone_label = QLabel("Phone Number:")
# Create a QLineEdit for phone number input
phone_input = QLineEdit()
phone_input.setPlaceholderText("(123) 456-7890") # Example format
phone_input.setInputMask("(999) 999-9999") # Mask for phone number input
phone_input.setToolTip("Enter your 10-digit phone number")
# Add widgets to layout
layout.addWidget(phone_label)
layout.addWidget(phone_input)
self.setLayout(layout)
self.setWindowTitle("Phone Number Input Example")
self.setGeometry(100, 100, 300, 150)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = PhoneNumberApp()
sys.exit(app.exec())I executed the above example code and added the screenshot below.

The input mask (999) 999-9999 ensures that only numbers can be entered and automatically formats them as a US phone number.
Read QComboBox Widget in PyQt6
Input Validators
When designing user interfaces, ensuring the correct input format is crucial. PyQt6 provides validators that restrict user input to specific formats. This prevents errors and enhances user experience.
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit
from PyQt6.QtGui import QIntValidator, QDoubleValidator, QRegularExpressionValidator
from PyQt6.QtCore import QRegularExpression
class ValidatorExample(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# Create layout
layout = QVBoxLayout()
# Integer input (age)
age_label = QLabel("Age:")
age_input = QLineEdit()
age_input.setPlaceholderText("25")
age_input.setValidator(QIntValidator(18, 120)) # Only allow ages 18-120
age_input.setToolTip("Enter your age (18-120)")
# Price input with double validator
price_label = QLabel("Price ($):")
price_input = QLineEdit()
price_input.setPlaceholderText("99.99")
price_input.setValidator(QDoubleValidator(0, 10000, 2)) # 0-10000 with 2 decimal places
price_input.setToolTip("Enter price (0-10000)")
# Email input with regular expression validator
email_label = QLabel("Email Address:")
email_input = QLineEdit()
email_input.setPlaceholderText("john.smith@example.com")
email_regex = QRegularExpression(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
email_input.setValidator(QRegularExpressionValidator(email_regex))
email_input.setToolTip("Enter a valid email address")
# Add widgets to layout
layout.addWidget(age_label)
layout.addWidget(age_input)
layout.addWidget(price_label)
layout.addWidget(price_input)
layout.addWidget(email_label)
layout.addWidget(email_input)
self.setLayout(layout)
self.setWindowTitle("Input Validation Example")
self.setGeometry(100, 100, 400, 200)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ValidatorExample()
sys.exit(app.exec())I executed the above example code and added the screenshot below.

By applying these validators, we ensure that the age, price, and email inputs accept only valid data, reducing errors in our application.
Custom Validation Logic
In some cases, built-in validators like QIntValidator or QRegularExpressionValidator might not be sufficient for your application’s needs. Custom validation logic allows developers to define specific rules for user input.
class PasswordInput(QLineEdit):
def __init__(self):
super().__init__()
self.setPlaceholderText("Enter a strong password")
self.setEchoMode(QLineEdit.EchoMode.Password)
self.textChanged.connect(self.validate_password)
self.setStyleSheet("border: 1px solid gray; border-radius: 5px; padding: 5px;")
def validate_password(self, password):
if len(password) < 8:
self.setStyleSheet("border: 1px solid red; border-radius: 5px; padding: 5px;")
self.setToolTip("Password must be at least 8 characters")
elif not any(c.isupper() for c in password):
self.setStyleSheet("border: 1px solid orange; border-radius: 5px; padding: 5px;")
self.setToolTip("Password must contain at least one uppercase letter")
elif not any(c.isdigit() for c in password):
self.setStyleSheet("border: 1px solid orange; border-radius: 5px; padding: 5px;")
self.setToolTip("Password must contain at least one number")
else:
self.setStyleSheet("border: 1px solid green; border-radius: 5px; padding: 5px;")
self.setToolTip("Strong password")
# Add to layout
password_label = QLabel("Password:")
password_input = PasswordInput()
layout.addWidget(password_label)
layout.addWidget(password_input)By implementing custom validation logic, we enhance user experience and ensure only valid, secure data is entered.
Read How to Install PyQt6 on Different Platforms?
Styling QLineEdit
Visual appearance plays a crucial role in professional applications. Here’s how to style your QLineEdit widgets effectively:
styled_input = QLineEdit()
styled_input.setPlaceholderText("Search products...")
styled_input.setStyleSheet("""
QLineEdit {
border: 2px solid #3498db;
border-radius: 15px;
padding: 8px 15px;
background-color: #f8f9fa;
color: #333;
font-size: 14px;
selection-background-color: #3498db;
}
QLineEdit:focus {
border: 2px solid #2980b9;
background-color: white;
}
QLineEdit:hover {
background-color: #e9ecef;
}
""")
search_label = QLabel("Product Search:")
layout.addWidget(search_label)
layout.addWidget(styled_input)Add Icons and Action Buttons
In modern UI design, text fields often include icons and action buttons for enhanced usability. This makes interfaces more intuitive by allowing users to perform actions directly within the input field.
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QAction
search_input = QLineEdit()
search_input.setPlaceholderText("Search companies...")
# Add search icon on the left
search_icon = QAction(QIcon("search_icon.png"), "Search", search_input)
search_input.addAction(search_icon, QLineEdit.ActionPosition.LeadingPosition)
# Add clear button on the right
clear_icon = QAction(QIcon("clear_icon.png"), "Clear", search_input)
clear_icon.triggered.connect(search_input.clear)
search_input.addAction(clear_icon, QLineEdit.ActionPosition.TrailingPosition)
# Add to layout
search_label = QLabel("Company Search:")
layout.addWidget(search_label)
layout.addWidget(search_input)This is a simple yet effective way to enhance text input fields in PyQt6 applications.
Check out Create a Basic Window in PyQt6
Password Fields and Echo Modes
In security-sensitive applications, such as login forms and authentication pages, it’s crucial to hide users’ passwords while typing. PyQt6 provides echo modes in QLineEdit to control how text is displayed in password fields.
# Standard password field
password_input = QLineEdit()
password_input.setPlaceholderText("Enter password")
password_input.setEchoMode(QLineEdit.EchoMode.Password) # Shows dots instead of characters
# Password field with reveal button
from PyQt6.QtWidgets import QHBoxLayout, QPushButton
password_container = QWidget()
password_layout = QHBoxLayout(password_container)
password_layout.setContentsMargins(0, 0, 0, 0)
secure_input = QLineEdit()
secure_input.setPlaceholderText("Enter your password")
secure_input.setEchoMode(QLineEdit.EchoMode.Password)
reveal_button = QPushButton("Show")
reveal_button.setCheckable(True)
reveal_button.setFixedWidth(60)
reveal_button.toggled.connect(lambda checked: secure_input.setEchoMode(
QLineEdit.EchoMode.Normal if checked else QLineEdit.EchoMode.Password
))
reveal_button.toggled.connect(lambda checked: reveal_button.setText(
"Hide" if checked else "Show"
))
password_layout.addWidget(secure_input)
password_layout.addWidget(reveal_button)
password_label = QLabel("Secure Password:")
layout.addWidget(password_label)
layout.addWidget(password_container)Read Create a Random Number Generator with QLCDNumber in PyQt6
Create Input Forms with QLineEdit
A registration form is an essential part of any application that requires user authentication. In this PyQt6 example, we create a graphical user interface (GUI) form that allows users to enter their details, including their name, email, username, and password, and submit the form for validation.
from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout
from PyQt6.QtCore import Qt
class RegistrationForm(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
form_layout = QVBoxLayout()
form_layout.setSpacing(10)
# Title
title = QLabel("New User Registration")
title.setStyleSheet("font-size: 18px; font-weight: bold;")
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
form_layout.addWidget(title)
# First Name
first_name_label = QLabel("First Name:")
self.first_name_input = QLineEdit()
self.first_name_input.setPlaceholderText("John")
form_layout.addWidget(first_name_label)
form_layout.addWidget(self.first_name_input)
# Last Name
last_name_label = QLabel("Last Name:")
self.last_name_input = QLineEdit()
self.last_name_input.setPlaceholderText("Smith")
form_layout.addWidget(last_name_label)
form_layout.addWidget(self.last_name_input)
# Email
email_label = QLabel("Email Address:")
self.email_input = QLineEdit()
self.email_input.setPlaceholderText("john.smith@example.com")
form_layout.addWidget(email_label)
form_layout.addWidget(self.email_input)
# Username
username_label = QLabel("Username:")
self.username_input = QLineEdit()
self.username_input.setPlaceholderText("johnsmith123")
form_layout.addWidget(username_label)
form_layout.addWidget(self.username_input)
# Password
password_label = QLabel("Password:")
self.password_input = QLineEdit()
self.password_input.setPlaceholderText("Enter a strong password")
self.password_input.setEchoMode(QLineEdit.EchoMode.Password) # Hide password
form_layout.addWidget(password_label)
form_layout.addWidget(self.password_input)
# Confirm Password
confirm_password_label = QLabel("Confirm Password:")
self.confirm_password_input = QLineEdit()
self.confirm_password_input.setPlaceholderText("Re-enter password")
self.confirm_password_input.setEchoMode(QLineEdit.EchoMode.Password)
form_layout.addWidget(confirm_password_label)
form_layout.addWidget(self.confirm_password_input)
# Submit Button
submit_button = QPushButton("Register")
submit_button.setStyleSheet("font-size: 14px; font-weight: bold; padding: 8px;")
submit_button.clicked.connect(self.register_user)
form_layout.addWidget(submit_button)
# Set layout
self.setLayout(form_layout)
self.setWindowTitle("User Registration")
self.setGeometry(100, 100, 400, 400)
def register_user(self):
first_name = self.first_name_input.text()
last_name = self.last_name_input.text()
email = self.email_input.text()
username = self.username_input.text()
password = self.password_input.text()
confirm_password = self.confirm_password_input.text()
if not all([first_name, last_name, email, username, password, confirm_password]):
print("All fields are required!")
elif password != confirm_password:
print("Passwords do not match!")
else:
print(f"User {username} registered successfully!")
if __name__ == "__main__":
app = QApplication([])
window = RegistrationForm()
window.show()
app.exec()Conclusion
In this tutorial, I explained how to create QLineEdit widget in PyQt6. I discussed creating our first QLineEdit, input validation and constraints, and styling QLineEdit. I also covered how to add icons and action button, password field and echo modes ,and create input forms with QLineEdit.
You may read:
- How to Create QPushButton Widget in PyQt6?
- How to Create QLabel Widget in PyQt6?
- Basic Widgets in PyQt6

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.