Sunday, May 5, 2024
HomePythonA Textual content Enter Fields to Your GUIs

A Textual content Enter Fields to Your GUIs


The QLineEdit class is a flexible software for single-line textual content enter. The widget facilitates textual content manipulation by supporting insertion, deletion, choice, and cut-copy-paste operations natively. You should utilize line edits when it is advisable to settle for textual content enter out of your customers in a PyQt/PySide software.

The widget is very customizable. You possibly can set it as much as embrace placeholder textual content, enter masks, enter validators, and extra. It additionally helps many keyboard shortcuts out of the field and is ready to course of customized ones. This function opens a possibility to reinforce person enter velocity and effectivity.

On this article, you’ll study the fundamentals of utilizing QLineEdit by going by way of its mostly used options and capabilities.

A line edit permits the person to enter and edit a single line of plain textual content with a helpful assortment of modifying functionalities, akin to insertion, deletion, choice, cut-copy-paste, and drag-and-drop operations.

If you happen to’ve used PyQt or PySide to create GUI functions in Python, then it would be possible that you simply already know concerning the QLineEdit class. This class lets you create line edits in your graphical interfaces (GUI) rapidly.

The QLineEidt class supplies two completely different constructors that you should use to create line edits in keeping with your wants:

The mum or dad widget can be the window or dialog the place it is advisable to place the road edit. The textual content could be a default textual content that may seem within the line edit while you run the appliance.

As an example easy methods to use the above constructors, we are able to code a demo instance:

python

from PyQt6.QtWidgets import QApplication, QLineEdit, QVBoxLayout, QWidget

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("QLineEdit Constructors")
        self.resize(300, 100)
        # Line edit with a mum or dad widget
        top_line_edit = QLineEdit(mum or dad=self)
        # Line edit with a mum or dad widget and a default textual content
        bottom_line_edit = QLineEdit(
            "Hi there! This can be a line edit.", mum or dad=self
        )

        format = QVBoxLayout()
        format.addWidget(top_line_edit)
        format.addWidget(bottom_line_edit)
        self.setLayout(format)

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, we first do the required imports after which outline the Window class inheriting from QWidget. Inside Window, we create two QLineEdit widgets.

To create the primary line edit, we use the primary constructor of QLineEdit, passing solely a mum or dad widget. For the second line editor, we use the second constructor, which requires the mum or dad widget and a default textual content. Observe that the textual content is a daily Python string.

Save the code to a file known as constructors.py file and run it out of your command line. You may get a window that appears one thing like this:

QLineEdit constructors example
Commonplace window exhibiting our two line edits.

The primary line edit has no textual content. Generally, that is how you’d create your line edits as a result of they’re designed for accepting enter. If you would like to simply show some textual content, then you should use a QLabel widget as a substitute. The second line edit shows the textual content that you simply handed to the constructor.

Each line edits are prepared for accepting enter textual content. Observe that you should use all the next keyboard shortcuts to optimize your textual content enter course of:

Keys Motion
Left Arrow Strikes the cursor one character to the left
Shift+Left Arrow Strikes and selects textual content one character to the left
Proper Arrow Strikes the cursor one character to the correct
Shift+Proper Arrow Strikes and selects textual content one character to the correct
House Strikes the cursor to the start of the road
Finish Strikes the cursor to the tip of the road
Backspace Deletes the character to the left of the cursor
Ctrl+Backspace Deletes the phrase to the left of the cursor
Delete Deletes the character to the correct of the cursor
Ctrl+Delete Deletes the phrase to the correct of the cursor
Ctrl+A Choose all
Ctrl+C Copies the chosen textual content to the clipboard
Ctrl+Insert Copies the chosen textual content to the clipboard
Ctrl+Okay Deletes to the tip of the road
Ctrl+V Pastes the clipboard textual content into the road edit
Shift+Insert Pastes the clipboard textual content into the road edit
Ctrl+X Deletes the chosen textual content and copies it to the clipboard
Shift+Delete Deletes the chosen textual content and copies it to the clipboard
Ctrl+Z Undoes the final operation
Ctrl+Y Redoes the final undone operation

That is loads of shortcuts! This desk is only a pattern of all of the options that the QLineEdit class supplies out of the field.

Along with these keyboard shortcuts, the QLineEdit class supplies a context menu that you would be able to set off by clicking on a line edit utilizing the correct button of your mouse:

QLineEdit context menu
QLineEdit with a context menu seen.

The built-in context menu supplies primary version choices, akin to minimize, copy, paste, and delete. It additionally has choices for undoing and redoing edits, and for choosing all of the content material of a given line edit.

Creating Non-Editable Line Edits

Typically, we have to make a line edit non-editable. By default, all line edits are editable as a result of their foremost use case is to supply textual content enter for the person. Nonetheless, in some conditions, a non-editable line edit may be helpful.

For instance, say that you simply’re making a GUI software that generates some restoration keys for the customers. The person should be capable to copy the important thing to a protected place in order that they will use it to recuperate entry in the event that they overlook their password. On this scenario, making a non-editable line edit can present an acceptable resolution.

To make a line edit read-only, we are able to use the readOnly property and its setter methodology setReadOnly() as within the following instance:

python

import secrets and techniques

from PyQt6.QtWidgets import (
    QApplication,
    QLabel,
    QLineEdit,
    QVBoxLayout,
    QWidget,
)

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Non-editable QLineEdit")
        self.resize(300, 100)
        non_editable_line_edit = QLineEdit(mum or dad=self)
        non_editable_line_edit.setReadOnly(True)
        non_editable_line_edit.setText(secrets and techniques.token_hex(16))

        format = QVBoxLayout()
        format.addWidget(QLabel(mum or dad=self, textual content="Your secret key:"))
        format.addWidget(non_editable_line_edit)
        self.setLayout(format)

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, we create a non-editable line edit by utilizing the setReadOnly() methodology. Once we set the readOnly property to True, our line edit will not settle for editions. It will solely enable us to pick out and duplicate its content material.

Go forward and run the appliance out of your command line to discover how this line edit works. You may get a window like the next:

Non-editable line edit
A read-only line edit with modifying disabled.

If you happen to play a bit with this line edit, you will quickly uncover that you would be able to’t change its textual content. You may additionally notice that the choices within the context menu are actually restricted to Copy and Choose All.

Creating Line Edits for Passwords

One other cool function of the QLineEdit class is that it lets you create textual content enter for passwords. This may be fairly handy for these functions that handle a number of customers, and every person must have entry credentials.

You possibly can create line edits for passwords by utilizing the echoMode() methodology. This methodology takes one of many following constants as an argument:

Fixed Worth Description
QLineEdit.EchoMode.Regular 0 Show characters as you enter them.
QLineEdit.EchoMode.NoEcho 1 Show no characters while you enter them.
QLineEdit.EchoMode.Password 2 Show platform-dependent password masks characters as a substitute of the characters you enter.
QLineEdit.EchoMode.PasswordEchoOnEdit 3 Show characters as you enter them whereas modifying. Show characters because the Password mode does when studying.

The Regular mode is the default. The NoEcho mode could also be applicable for crucial passwords the place even the size of the password needs to be stored secret.
The Password mode is acceptable for many password use circumstances, nevertheless PasswordEchoOnEdit can be utilized as a substitute if it is advisable to give customers some affirmation of what they’re typing.

Here is a pattern app that reveals a person and password type:

python

from PyQt6.QtWidgets import (
    QApplication,
    QFormLayout,
    QLineEdit,
    QWidget,
)

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Password QLineEdit")
        self.resize(300, 100)
        username_line_edit = QLineEdit(mum or dad=self)
        password_line_edit = QLineEdit(mum or dad=self)
        password_line_edit.setEchoMode(QLineEdit.EchoMode.Password)

        format = QFormLayout()
        format.addRow("Username:", username_line_edit)
        format.addRow("Password:", password_line_edit)
        self.setLayout(format)

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, you name setEchoMode() on the password_line_edit widget utilizing the Password mode as an argument. While you run this code out of your command line, you get the next window in your display screen:

Password line edit
Window with a username and password line edit.

The username_line_edit line edit is in Regular mode, so we are able to see the characters as we sort them in. In distinction, the Password line edit is in Password mode. On this case, after we enter a personality, the road edit reveals the platform’s character for passwords.

Manipulating the Enter in a Line Edit

You possibly can change the textual content of a line edit utilizing the setText() or insert() strategies. You possibly can retrieve the textual content with the textual content() methodology. Nonetheless, these usually are not the one operations that you would be able to carry out with the textual content of a line edit.

The next desk reveals a abstract of among the mostly used strategies for textual content manipulation in line edits:

Methodology Description
setText(textual content) Units the textual content of a line edit to textual content, clears the choice, clears the undo/redo historical past, strikes the cursor to the tip of the road, and resets the modified property to false.
insert(textual content) Deletes any chosen textual content, inserts textual content, and validates the end result. Whether it is legitimate, it units it as the brand new contents of the road edit.
clear() Clears the contents of the road edit.
copy() Copies the chosen textual content to the clipboard.
minimize() Copies the chosen textual content to the clipboard and deletes it from the road edit.
paste() Inserts the clipboard’s textual content on the cursor place, deleting any chosen textual content.
redo() Redoes the final operation if redo is obtainable. Redo turns into obtainable as soon as the person has carried out a number of undo operations on textual content within the line edit.
undo() Undoes the final operation if undo is obtainable. Undo turns into obtainable as soon as the person has modified the textual content within the line edit.
selectAll() Selects all of the textual content and strikes the cursor to the tip.

You should utilize any of those strategies to govern the textual content of a line edit out of your code. Take into account the next instance the place you’ve got two line edits and two buttons that make the most of among the above strategies to repeat some textual content from one line edit to the opposite:

python

from PyQt6.QtWidgets import (
    QApplication,
    QGridLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QWidget,
)

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Copy and Paste")
        self.resize(300, 100)

        self.source_line_edit = QLineEdit(mum or dad=self)
        self.source_line_edit.setText("Hi there, World!")
        self.dest_line_edit = QLineEdit(mum or dad=self)

        copy_button = QPushButton(mum or dad=self, textual content="Copy")
        paste_button = QPushButton(mum or dad=self, textual content="Paste")

        copy_button.clicked.join(self.copy)
        paste_button.clicked.join(self.paste)

        format = QGridLayout()
        format.addWidget(self.source_line_edit, 0, 0)
        format.addWidget(copy_button, 0, 1)
        format.addWidget(self.dest_line_edit, 1, 0)
        format.addWidget(paste_button, 1, 1)
        self.setLayout(format)

    def copy(self):
        self.source_line_edit.selectAll()
        self.source_line_edit.copy()

    def paste(self):
        self.dest_line_edit.clear()
        self.dest_line_edit.paste()

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, we create two line edits. The primary one will maintain some pattern textual content. The second line edit will obtain the textual content. Then, we create two buttons and join their clicked alerts to the copy() and paste() slots.

Contained in the copy() methodology we first choose all of the textual content from the supply line edit. Then we use the copy() methodology to repeat the chosen textual content to the clipboard. In paste(), we name clear() on the vacation spot line edit to take away any earlier textual content. Then, we use the paste() methodology to repeat the clipboard’s content material.

Go forward and run the appliance. You may get the next window in your display screen:

QLineEdit Copy and Paste
QLineEdit with Copy & Paste buttons hooked up to handlers.

As soon as you’ve got run the app, then you’ll be able to click on the Copy button to repeat the textual content within the first line edit. Subsequent, you’ll be able to click on the Paste button to stick the copied textual content to the second line edit. Go forward and provides it a attempt!

Over 10,000 builders have purchased Create GUI Purposes with Python & Qt!

Have a look

Downloadable e book (PDF, ePub) & Full Supply code

[[ discount.discount_pc ]]% OFF for
the following [[ discount.duration ]]
[[discount.description ]]
with the code [[ discount.coupon_code ]]

Buying Energy Parity

Builders in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & programs
with code [[ discount.coupon_code ]]

Aligning and Formatting the Textual content in a Line Edit

You may also align and format the textual content in a line edit. For instance, for textual content alignment, you should use the setAlignment() methodology with a number of alignment flags. A number of the most helpful flags that yow will discover within the Qt.AlignmentFlag namespace contains the next:

Flag Description
AlignLeft Aligns with the left edge.
AlignRight Aligns with the correct edge.
AlignHCenter Facilities horizontally within the obtainable house.
AlignJustify Justifies the textual content within the obtainable house.
AlignTop Aligns with the highest.
AlignBottom Aligns with the underside.
AlignVCenter Facilities vertically within the obtainable house.
AlignCenter Facilities in each dimensions.

If you wish to apply a number of alignment flags to a given line edit, you do not have to name setAlignment() a number of instances. You possibly can simply use the bitwise OR operator (|) to mix them. Take into account the next instance:

python

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

class Window(QLineEdit):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Aligning Textual content")
        self.resize(300, 100)
        self.setText("Hi there, World!")
        self.setAlignment(Qt.AlignmentFlag.AlignCenter)

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, we use a QLineEdit as the one part of our app’s GUI. Utilizing the setAlignment() methodology, we heart the "Hi there, World!" message in each instructions, horizontally and vertically. To do that, we use the AlignCenter flag. Here is what the app appears like:

QLineEdit text alignment
QLineEdit with textual content alignment set.

Go forward and play with different flags to see their impact on the textual content alignment. Use the | bitwise operator to mix a number of alignment flags.

Line edits even have a textMargins property that you would be able to tweak to customise the textual content alignment utilizing particular values. To set margin values on your textual content, you should use the setTextMargins() methodology, which has the next signatures:

The primary signature lets you present 4 integer values because the left, high, proper, and backside margins for the textual content. The second signature accepts a QMargins object as an argument. To construct this object, you should use 4 integer values with the identical that means because the left, high, proper, and backside arguments within the first signature.

Here is an instance of easy methods to set customized margins for the textual content in a line edit:

python

from PyQt6.QtWidgets import QApplication, QLineEdit

class Window(QLineEdit):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Aligning Textual content")
        self.resize(300, 100)
        self.setText("Hi there, World!")
        self.setTextMargins(30, 30, 0, 0)

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, you set the left and high margins to customized values. Here is how this app appears while you run it:

QLineEdit text margins
QLineEdit with textual content margins added.

Utilizing the setTextMargins() methodology, we are able to place the textual content within the desired place in a line edit, which can be a requirement in some conditions.

Connecting Alerts and Slots

While you’re making a GUI software and it is advisable to use line edits, it’s possible you’ll must carry out actions when the person enters or modifies the content material of the road edit. To do that, it is advisable to join among the alerts of the road edit to particular slots or features.

Relying on particular person occasions, the QLineEdit class can emit a number of completely different alerts. Here is is a abstract of those alerts and their corresponding that means:

Sign Emitted
textChanged(textual content) Each time the person adjustments the textual content both manually or programmatically. The textual content argument is the brand new textual content.
textEdited(textual content) Each time the person edits the textual content manually. The textual content argument is the brand new textual content.
editingFinished When the person presses the Return or Enter key, or when the road edit loses focus, and its contents have modified because the final time this sign was emitted.
inputRejected When the person presses a key that’s an unacceptable enter.
returnPressed When the person presses the Return or Enter key.
selectionChanged When the choice adjustments.

We are able to join both of those alerts with any slot. A slot is a technique or perform that performs a concrete motion in your software. We are able to join a sign and a slot in order that the slot will get known as when the sign will get emitted. Here is the required syntax to do that:

python

line_edit.<sign>.join(<methodology>)

On this assemble, line_edit is the QLineEdit object that we have to join with a given slot. The <sign> placeholder may be any of the abovementioned alerts. Lastly, <methodology> represents the goal slot or methodology.

Let’s write an instance that places this syntax into motion. For this instance, we’ll join the textEdited sign with a way that updates the textual content of a QLabel to match the textual content of our line edit:

python

from PyQt6.QtWidgets import (
    QApplication,
    QLabel,
    QLineEdit,
    QVBoxLayout,
    QWidget,
)

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Sign and Slot")
        self.resize(300, 100)

        self.line_edit = QLineEdit(mum or dad=self)
        self.label = QLabel(mum or dad=self)
        self.line_edit.textEdited.join(self.update_label)

        format = QVBoxLayout()
        format.addWidget(self.line_edit)
        format.addWidget(self.label)
        self.setLayout(format)

    def update_label(self):
        self.label.setText(self.line_edit.textual content())

app = QApplication([])
window = Window()
window.present()
app.exec()

On this instance, we join the road edit’s textEdited sign with the update_label() methodology, which units the label’s textual content to match the textual content we enter in our line edit. Go forward and run the app. Then, enter some textual content within the line edit and see what occurs with the label on the backside of the app’s window.

Validating Enter in Line Edits

We are able to present enter validators to our line edits utilizing the setValidator() methodology. This methodology takes a QValidator object as an argument. PyQt has a couple of built-in validators that you should use instantly on a line edit:

Validator objects course of the enter to verify whether or not it is legitimate. Generally, validator object has three potential states:

Fixed Worth Description
QValidator.State.Invalid 0 The enter is invalid.
QValidator.State.Intermediate 1 The enter is a legitimate intermediate worth.
QValidator.State.Acceptable 2 The enter is appropriate as a ultimate end result.

While you set a validator to a given line edit, the person might change the content material to any Intermediate worth throughout modifying. Nonetheless, they cannot edit the textual content to a worth that’s Invalid. The road edit will emit the returnPressed and editingFinished alerts solely when the validator validates enter as Acceptable.

Here is an instance the place we use a QIntValidator and a QRegularExpressionValidator

python

from PyQt6.QtCore import QRegularExpression
from PyQt6.QtGui import QIntValidator, QRegularExpressionValidator
from PyQt6.QtWidgets import (
    QApplication,
    QFormLayout,
    QLabel,
    QLineEdit,
    QWidget,
)

class Window(QWidget):
    def __init__(self, mum or dad=None):
        tremendous().__init__(mum or dad)
        self.setWindowTitle("Enter Validators")
        self.resize(300, 100)

        self.int_line_edit = QLineEdit(mum or dad=self)
        self.int_line_edit.setValidator(QIntValidator())

        self.uppercase_line_edit = QLineEdit(mum or dad=self)
        input_validator = QRegularExpressionValidator(
            QRegularExpression("[A-Z]+"), self.uppercase_line_edit
        )
        self.uppercase_line_edit.setValidator(input_validator)
        self.uppercase_line_edit.returnPressed.join(self.update_label)

        self.signal_label = QLabel(mum or dad=self)

        format = QFormLayout()
        format.addRow("Integers:", self.int_line_edit)
        format.addRow("Uppercase letters:", self.uppercase_line_edit)
        format.addRow("Sign:", self.signal_label)
        self.setLayout(format)

    def update_label(self):
        self.signal_label.setText("Return pressed!")

if __name__ == "__main__":
    app = QApplication([])
    window = Window()
    window.present()
    app.exec()

On this instance, we’ve two line edits. Within the first line edit, we have used a QIntValidator object. This manner, the road edit will solely settle for legitimate integer numbers. If you happen to attempt to sort in one thing completely different, then the road edit will not settle for your enter.

Within the second line edit, we have used a QRegularExpressionValidator. On this particular case, the common expression accepts a number of uppercase letters. Once more in case you attempt to enter one thing else, then the road edit will not settle for the enter.

The QLabel will present the textual content Return pressed! if the enter within the second line edit is legitimate and also you press the Enter key. Here is what the app appears like:

QLineEdit with input validator
QLineEdit with enter validator.

Validators present a fast strategy to limit the person enter and set our personal validation guidelines. This manner, we are able to guarantee legitimate person enter in our functions.

Conclusion

Line edits are fairly helpful widgets in any GUI software. They permit textual content enter by way of a single-line editor that has many cool options.

On this tutorial, you’ve got realized easy methods to create, use, and customise your line edits whereas constructing a GUI software with PyQt/PySide.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments