[파이썬] PyQt 텍스트 입력 (`QLineEdit`) 위젯

In this blog post, we will explore how to use the QLineEdit widget in PyQt. The QLineEdit widget is used to create a single-line text input field in PyQt applications. It provides a simple and user-friendly way for users to enter text.

Getting Started

To use the QLineEdit widget, we need to first import the QLineEdit class from the PyQt library. Here’s an example of how to import the necessary modules:

from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit
import sys

Creating a QLineEdit Widget

To create a QLineEdit widget, we first need to create an instance of the QLineEdit class. We can do this by calling the constructor of the class:

text_input = QLineEdit()

Setting the Placeholder Text

The QLineEdit widget allows us to set a placeholder text, which provides a hint to the user about the expected input. We can set the placeholder text using the setPlaceholderText method:

text_input.setPlaceholderText("Enter your name")

Retrieving the User Input

To retrieve the text entered by the user in the QLineEdit widget, we can use the text method:

user_input = text_input.text()

Connecting Signals and Slots

We can connect signals and slots to perform actions when certain events occur in the QLineEdit widget. For example, we can connect the textChanged signal to update a label whenever the user enters or changes the text:

text_input.textChanged.connect(update_label)
def update_label():
    label.setText(text_input.text())

Styling the QLineEdit Widget

We can use Cascading Style Sheets (CSS) to style the QLineEdit widget. For example, we can set the background color, font size, and border using the setStyleSheet method:

text_input.setStyleSheet("background-color: #f2f2f2; font-size: 14px; border: 1px solid #ccc;")

Conclusion

In this blog post, we learned how to use the QLineEdit widget in PyQt. We explored how to create a QLineEdit widget, set placeholder text, retrieve user input, connect signals and slots, and style the widget using CSS. The QLineEdit widget provides a simple and versatile way to handle text input in PyQt applications.

I hope you found this blog post helpful. Happy coding with PyQt!