Not retrieving data from QDialog when clicking on Cancel button

  • Hello,
    I'm using Pyside2, python 3.8

    I have a QMainWindow with a pushbutton, when the button is clicked, a QDialog shows up

    My Dialog form

    I want to retrieve the texts in the QLineEdits when the Add button is clicked. I've managed to do that using the following code:

    class Dialog(QtWidgets.QDialog, Ui_Dialog):
    	def __init__(self, parent=None):
    		super(Dialog, self).__init__(parent)
    class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    	def __init__(self, parent=None):
    		super(MainWindow, self).__init__(parent)
    	def showDialog(self):
    		d = Dialog(self)
    		self.Data = [d.LineEdit1.text(), d.LineEdit2.text(), d.LineEdit3.text()]
    	def foo(self, foo):
    		for txt in foo:
    if __name__== '__main__':
    	app = QtWidgets.QApplication(sys.argv)
    	mainWin = MainWindow()

    As I said, this works, but the problem is that it also works when I hit cancel.

    I want the func function in my MainWindow class to run only if I hit the Add button and only that.

    How Can I achieve that ?


  • Lifetime Qt Champion


    exec() has a return value, maybe tuple in Python. Use that to determine what was pressed.

  • Hi @SGaist ,

    How can I retrieve what button has been pressed ?

  • @hachbani
    As @SGaist said. Make sure your Add button calls accept(), or done() with a particular value, to exit the dialog. And Cancel button should call reject(). Not just close() as you have now. That is what QDialogs should do. Then the return result of the exec() will give that value to the caller, for you to examine.

Log in to reply