Reputation: 356
I'm using Pyside2, Python 3.8
I have a QMainWindow
with a pushbutton
, when the button is clicked
, a QDialog
shows up
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?
Upvotes: 0
Views: 45
Reputation: 48335
The correct way to close QDialogs when connecting to buttons is through accept()
and reject()
, and correctly catch the return value from `exec().
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.AddButton.clicked.connect(self.accept)
self.CancelButton.clicked.connect(self.reject)
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
# ...
def showDialog(self):
d = Dialog(self)
if d.exec_():
self.Data = [d.LineEdit1.text(), d.LineEdit2.text(), d.LineEdit3.text()]
self.func(self.Data)
# ...
You should also consider using QDialogButtonBox.
I suggest you to use capitalized names only for classes, not for variable names. Read more on the official Style Guide for Python Code
Upvotes: 1