Home » Tutorial on PyQt6 QLineEdit

Tutorial on PyQt6 QLineEdit

Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
1 Year Subscription
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

QLineEdit is a widget in PyQt6 used for single-line text input.

It supports basic text handling, placeholder text, input masks, and advanced features like password fields, text validation, and signals for interactive applications.

In this tutorial, we’ll cover:

1. Basics of QLineEdit

QLineEdit is a simple single-line text box for user input. You can set and retrieve text using the setText() and text() methods.

Example: Basic QLineEdit Setup

from PyQt6.QtWidgets import QApplication, QLineEdit, QMainWindow

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Basic QLineEdit Example")
    window.setGeometry(100, 100, 300, 200)

    line_edit = QLineEdit(window)
    line_edit.setGeometry(50, 50, 200, 30)
    line_edit.setText("Hello, PyQt6!")

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A window with a QLineEdit pre-filled with “Hello, PyQt6!”.

2. Adding Placeholder Text

Placeholder text is a hint shown in the QLineEdit when it is empty.

Example: Adding Placeholder Text

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 200, 30)
line_edit.setPlaceholderText("Enter your text here...")

Output:

  • A text box with a placeholder saying “Enter your text here…” until the user types something.

3. Handling Input with Signals

QLineEdit provides signals like textChanged, returnPressed, and editingFinished to handle user interactions.

Example: Handling Text Changes

from PyQt6.QtWidgets import QApplication, QLineEdit, QMainWindow
from PyQt6.QtCore import Qt

def on_text_change(text):
    print(f"Text changed: {text}")

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Text Change Example")
    window.setGeometry(100, 100, 300, 200)

    line_edit = QLineEdit(window)
    line_edit.setGeometry(50, 50, 200, 30)
    line_edit.textChanged.connect(on_text_change)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • Prints the text to the console as the user types.

Example: Handling Return Key Press

def on_return_pressed():
    print("Return key pressed!")

line_edit.returnPressed.connect(on_return_pressed)

4. Password Fields

You can mask input in a QLineEdit to create a password field.

Example: Password Field

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 200, 30)
line_edit.setEchoMode(QLineEdit.EchoMode.Password)

Output:

  • Text input will be replaced by dots or asterisks, depending on the system style.

5. Text Validation

QLineEdit allows you to validate input using regular expressions or custom validators.

Example: Numeric Validation

from PyQt6.QtWidgets import QLineEdit, QMainWindow, QApplication
from PyQt6.QtGui import QIntValidator

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Numeric Validation Example")
    window.setGeometry(100, 100, 300, 200)

    line_edit = QLineEdit(window)
    line_edit.setGeometry(50, 50, 200, 30)
    line_edit.setValidator(QIntValidator(0, 100))  # Accepts integers from 0 to 100

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • The text box accepts only integers between 0 and 100.

Example: Custom Regular Expression Validation

from PyQt6.QtGui import QRegularExpressionValidator
from PyQt6.QtCore import QRegularExpression

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 200, 30)
regex = QRegularExpression("[a-zA-Z]{5,10}")  # Accepts 5-10 alphabetic characters
line_edit.setValidator(QRegularExpressionValidator(regex))

6. Using Input Masks

Input masks enforce a specific input format.

Example: Date Input Mask

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 200, 30)
line_edit.setInputMask("0000-00-00")  # Enforces YYYY-MM-DD format

Output:

  • The text box accepts input in the format YYYY-MM-DD.

7. Styling QLineEdit

You can customize the appearance of QLineEdit using setStyleSheet().

Example: Styling QLineEdit

line_edit.setStyleSheet("""
    QLineEdit {
        background-color: lightyellow;
        border: 2px solid blue;
        border-radius: 5px;
        font-size: 16px;
    }
    QLineEdit:focus {
        border-color: green;
    }
""")

8. Practical Examples

Example 1: Search Box with a Button

from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton

def on_search():
    text = line_edit.text()
    print(f"Searching for: {text}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Search Box Example")
window.setGeometry(100, 100, 300, 200)

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 150, 30)
line_edit.setPlaceholderText("Enter search term...")

button = QPushButton("Search", window)
button.setGeometry(210, 50, 70, 30)
button.clicked.connect(on_search)

window.show()
app.exec()

Output:

  • Clicking “Search” prints the entered text to the console.

Example 2: Dynamic Character Counter

from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QLabel

def update_character_count():
    count = len(line_edit.text())
    label.setText(f"Characters: {count}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Character Counter Example")
window.setGeometry(100, 100, 300, 200)

line_edit = QLineEdit(window)
line_edit.setGeometry(50, 50, 200, 30)
line_edit.textChanged.connect(update_character_count)

label = QLabel("Characters: 0", window)
label.setGeometry(50, 90, 200, 30)

window.show()
app.exec()

Output:

  • Displays the number of characters typed in real-time.

Example 3: Login Form

from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton, QLabel

def on_login():
    username = username_edit.text()
    password = password_edit.text()
    if username == "admin" and password == "password":
        label.setText("Login Successful!")
    else:
        label.setText("Invalid Credentials")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Login Form")
window.setGeometry(100, 100, 300, 200)

username_edit = QLineEdit(window)
username_edit.setGeometry(50, 50, 200, 30)
username_edit.setPlaceholderText("Username")

password_edit = QLineEdit(window)
password_edit.setGeometry(50, 90, 200, 30)
password_edit.setPlaceholderText("Password")
password_edit.setEchoMode(QLineEdit.EchoMode.Password)

button = QPushButton("Login", window)
button.setGeometry(100, 130, 100, 30)
button.clicked.connect(on_login)

label = QLabel("", window)
label.setGeometry(50, 170, 200, 30)

window.show()
app.exec()

Output:

  • A login form with validation.

Summary

In this tutorial, we covered:

  1. Basics of QLineEdit: Creating text input boxes and setting text.
  2. Placeholder Text: Adding hints for users.
  3. Signals: Handling events like textChanged and returnPressed.
  4. Password Fields: Masking input for sensitive data.
  5. Text Validation: Enforcing specific formats with validators.
  6. Input Masks: Restricting input to predefined patterns.
  7. Styling: Customizing appearance with CSS.
  8. Practical Examples: Building search boxes, character counters, and login forms.

QLineEdit is a versatile widget that plays a key role in interactive PyQt6 applications, enabling robust user input handling.

 

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More