PyQt5 - QLineEdit

PyQt5 - QLineEdit

QLineEdit is a widget provided by PyQt5 that allows the user to input and edit a single line of plain text. Here's a brief introduction to QLineEdit and its features:

Basic Usage of QLineEdit:

  1. Installation:

    First, ensure you have PyQt5 installed:

    pip install pyqt5 pyqt5-tools 
  2. Simple Application:

    A basic example of how to use QLineEdit:

    import sys from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit, QVBoxLayout, QLabel class App(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): layout = QVBoxLayout() self.line_edit = QLineEdit(self) self.label = QLabel(self) layout.addWidget(self.line_edit) layout.addWidget(self.label) self.line_edit.textChanged.connect(self.on_text_changed) self.setLayout(layout) self.setWindowTitle('QLineEdit Example') self.show() def on_text_changed(self, text): self.label.setText(text) if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) 

    In this example, when the text in QLineEdit changes, it gets reflected in a QLabel below it. This is done using the textChanged signal of QLineEdit.

Notable Features and Methods of QLineEdit:

  • Placeholder Text: You can set a placeholder text which appears when the QLineEdit is empty:

    self.line_edit.setPlaceholderText("Enter text here...") 
  • Getting and Setting Text:

    To retrieve the text:

    text = self.line_edit.text() 

    To set the text:

    self.line_edit.setText("Initial Text") 
  • Read-only Mode:

    If you want the QLineEdit to be read-only:

    self.line_edit.setReadOnly(True) 
  • Password Mode:

    You can set the QLineEdit to display its content as dots, useful for password fields:

    self.line_edit.setEchoMode(QLineEdit.Password) 
  • Validation:

    QLineEdit can work with QValidator objects to restrict input. For instance, to allow only integer input:

    from PyQt5.QtGui import QIntValidator self.line_edit.setValidator(QIntValidator()) 
  • Clear Button:

    You can enable a clear button inside the QLineEdit which appears when there's text and allows the user to clear the content with a single click:

    self.line_edit.setClearButtonEnabled(True) 

This is a brief introduction to QLineEdit in PyQt5. To exploit its full potential, you might want to refer to the official documentation or comprehensive PyQt5 tutorials.


More Tags

pkcs#12 node-gyp average android-gallery onpress ratingbar svg qt confluent-platform stdout

More Programming Guides

Other Guides

More Programming Examples