Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

python - Not retrieve data from QDialog to QMainWindow when hitting Cancel button

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...