To retrieve the text from a QLineEdit widget in Python, you can use the text()
method. Here’s an example:
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QLineEdit, QPushButton
def get_line_edit_text():
text = line_edit.text()
print(f"The text is: {text}")
# Create the application
app = QApplication(sys.argv)
# Create the main window
window = QMainWindow()
# Create a QLineEdit widget
line_edit = QLineEdit(window)
line_edit.setGeometry(10, 10, 200, 30)
# Create a QPushButton to retrieve the text
button = QPushButton("Get Text", window)
button.setGeometry(10, 50, 100, 30)
button.clicked.connect(get_line_edit_text)
# Show the main window
window.show()
# Run the application event loop
sys.exit(app.exec_())
In the above code:
- First, you import the necessary modules, including
QApplication
,QMainWindow
,QLineEdit
, andQPushButton
, from PyQt5. - Define a function called
get_line_edit_text()
that retrieves the text from the QLineEdit widget using thetext()
method. In the example, it simply prints the text to the console. - Create the application using
QApplication(sys.argv)
. - Create the main window using
QMainWindow()
. - Create a QLineEdit widget and set its geometry using the
setGeometry()
method. - Create a QPushButton to retrieve the text and set its geometry. Connect the
clicked
signal of the button to theget_line_edit_text()
function. - Show the main window using
window.show()
. - Run the application event loop using
sys.exit(app.exec_())
. This allows the window to be displayed and handles user interactions.
When you run the code, you can enter text into the QLineEdit widget. Clicking the “Get Text” button will invoke the get_line_edit_text()
function and print the retrieved text to the console.
You can modify the get_line_edit_text()
function to perform any desired processing or use the retrieved text in your application logic.
+ There are no comments
Add yours