You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5技术问题:如何将QLineEdit控件内容转换为字符串类型

Fixing QLineEdit Text Retrieval in PyQt5

Hey there! I can see you're just getting started with Python and PyQt5, and you're stuck on pulling text from a QLineEdit—let's get this sorted out quickly.

The Core Issue

Right now, you're doing str(lineEdit_a_a) which converts the QLineEdit widget object itself to a string (that's why you're seeing something like <PyQt5.QtWidgets.QLineEdit object at 0x...> instead of the user's input). To get the actual text the user typed, you need to use the text() method built into QLineEdit.

Another Key Problem

Your main_body variable is defined when the program starts, before the user has a chance to enter any text. Even if you fixed the text retrieval, it would still use the empty initial value of the QLineEdit. You need to move the text retrieval and string concatenation inside your button's click handler so it runs every time the user clicks "Create text"—that way you get the latest input.

Modified Code Snippet

Here's how to adjust your code to make it work:

from PyQt5 import QtWidgets, QtCore
import sys

app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setWindowTitle("Fill-in-form")
window.resize(600, 600)

btnQuit = QtWidgets.QPushButton("Close the window")
label_a = QtWidgets.QLabel("Enter the driver's name")
label_a_a = QtWidgets.QLabel("Name:")
lineEdit_a_a = QtWidgets.QLineEdit()

set_5 = "kg, to the driver "

class MyClass(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)
    
    @QtCore.pyqtSlot()
    def on_clicked(self):
        # Get the current text from the QLineEdit here
        str_1 = lineEdit_a_a.text()
        # Build the main body with the latest input
        main_body = set_5 + str_1
        print(main_body) # Now this will show the expected result!

obj = MyClass()
btnCreateText = QtWidgets.QPushButton("Create text")
btnCreateText.clicked.connect(obj.on_clicked)

vbox = QtWidgets.QVBoxLayout()
vbox.addWidget(label_a)
vbox.addWidget(label_a_a)
vbox.addWidget(lineEdit_a_a)
vbox.addWidget(btnCreateText)
vbox.addWidget(btnQuit)

window.setLayout(vbox)
btnQuit.clicked.connect(app.quit)
window.show()
sys.exit(app.exec_())

What Changed?

  • Removed the initial str_1 = str(lineEdit_a_a) and main_body definitions—we don't need them until the button is clicked.
  • In the on_clicked method, we use lineEdit_a_a.text() to fetch the current input text.
  • We build main_body inside the click handler so it always uses the most recent text the user entered.

This should solve your problem and let you generate the text your friend needs for their work forms. Happy coding!

内容的提问来源于stack exchange,提问作者val

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:56:12