Skip to main content
 首页 » 编程设计

python之从 QLineEdit 中提取文本

2024年11月01日1252php

我用一个简单的 QLineEdit 和 QbuttonBox(分别是 lineEdit 和 buttonBox)创建了一个对话框,现在我尝试在按下 OK 时使用行编辑中的内容。它只是空白,在执行过程中不打印,并在 print(base) 的底部打印“无”。冲浪并找到了 text() 但仍然没有爱。任何帮助表示赞赏。

from PyQt4 import QtGui, QtCore 
import sys 
 
import x 
 
class Dialog(QtGui.QDialog, x.Ui_Dialog): 
 
    def __init__(self): 
        super(Dialog, self).__init__() 
        self.setupUi(self) 
        global base 
        base = self.buttonBox.accepted.connect(self.go) 
 
 
    def go(self): 
        what = self.lineEdit.text() 
        return what 
        print(what) 
 
 
 
app = QtGui.QApplication(sys.argv) 
form = Dialog() 
form.show() 
app.exec_() 
 
print(base) 

请您参考如下方法:

示例代码大部分是正确的,除了 go() 方法在它有机会打印任何东西之前返回。因此,如果您删除该行,它应该会按预期工作,即:

class Dialog(QtGui.QDialog, x.Ui_Dialog): 
    def __init__(self): 
        super(Dialog, self).__init__() 
        self.setupUi(self) 
        self.buttonBox.accepted.connect(self.go) 
 
    def go(self): 
        what = self.lineEdit.text() 
        print(what) 

此外,当您将信号连接到处理程序时,获取返回值毫无意义。如果连接无效,它只会引发错误。

编辑:

如果您想从对话框外部访问行编辑的文本,那么您真的不需要信号。只需确保对话框阻塞,直到用户输入文本,然后直接访问行编辑:

dialog = Dialog() 
if dialog.exec_() == QtGui.QDialog.Accepted: 
     text = dialog.lineEdit.text() 
     # do stuff with text... 
else: 
     print('cancelled')