Search code examples
pythonpython-3.xpyqt4qlineeditqdialog

Pulling text from QLineEdit


I made a dialog with a simple QLineEdit and QbuttonBox (lineEdit and buttonBox respectively), now I'm trying to use what is in the line edit when I press OK. It simply comes out blank and doesn't print during go and prints "None" for the bottom of print(base). Surfed and found the text() but still no love. Any help is appreciated.

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)

Solution

  • The example code is mostly correct, except that the go() method is returning before it has a chance to print anything. So if you remove that line, it should work as expected, i.e:

    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)
    

    Also, there is no point in grabbing the return value when you connect a signal to a handler. If the connection is invalid, it will just raise an error.

    EDIT:

    If you want to access the text of the line-edit from outside of the dialog, then you don't really need a signal. Just make sure the dialog blocks until the user has entered the text, and then access the line-edit directly:

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