Problems with Open-Source Downloads read https://www.qt.io/blog/problem-with-open-source-downloads and https://forum.qt.io/post/638946

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)
    		self.setupUi(self)
    		self.AddButton.clicked.connect(self.close)
    		self.CancelButton.clicked.connect(self.close)
    
    class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    	def __init__(self, parent=None):
    		super(MainWindow, self).__init__(parent)
    		self.setupUi(self)
    		self.ShowDialogButton.clicked.connect(self.showDialog)
    
    	def showDialog(self):
    		d = Dialog(self)
    		d.exec_()
    		self.Data = [d.LineEdit1.text(), d.LineEdit2.text(), d.LineEdit3.text()]
    		self.func(self.Data)
    
    	def foo(self, foo):
    		for txt in foo:
    			print(txt)
    
    if __name__== '__main__':
    	app = QtWidgets.QApplication(sys.argv)
    	mainWin = MainWindow()
    	mainWin.show()
    	sys.exit(app.exec_())
    

    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 ?

    Thanks;


  • Lifetime Qt Champion

    Hi,

    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