Search code examples
pythonqtpyqtpyqt4pyqt5

access inputted text from user with pyqt5


I am trying to access inputted text from user with following code:

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        self.textEdit = QtWidgets.QTextEdit()
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.mytext = self.textEdit.toPlainText()
        self.pushButton.clicked.connect(self.mainjob)

    def mainjob(self):
        print(self.mytext)

but i get empty string in result.


Solution

  • The problem is that you are setting self.mytext when the dialog is created and at that point the text edit widget has just been created and is thus empty. To get the current text when the button is pressed the mainjob function needs to get the text at that time.

    class Ui_Dialog(object):
        def setupUi(self, Dialog):
            self.textEdit = QtWidgets.QTextEdit()
            self.pushButton = QtWidgets.QPushButton(Dialog)
            self.pushButton.clicked.connect(self.mainjob)
    
        def mainjob(self):
            print(self.textEdit.toPlainText())