Execute Function After Click Ok (Qdialogbuttonbox)

i am using python 2.7 with PyQT5, this is my button:

self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(50, 240, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.buttonBox.clicked.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)

etc....

if __name__ == "__main__":

app = QApplication(sys.argv)
window = QDialog()
ui = Ui_Dialog()
ui.setupUi(window)

window.show()
sys.exit(app.exec_())

how can I execute a function after click OK??

2

2 Answers

Don't connect to buttonBox.clicked, because that will be called for every button.

Your button-box connections should look like this:

    self.buttonBox.accepted.connect(Dialog.accept)
    self.buttonBox.rejected.connect(Dialog.reject)

To run a function/slot when the dialog is accepted (i.e. only when the OK button is clicked), do this:

    self.accepted.connect(some_function)

If you want to pass a parameter, use a lambda:

    self.accepted.connect(lambda: some_function(param))
3

You buttonBox setup should look like

self.buttonBox.clicked.connect(Dialog.accept)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(Dialog.reject)

where self.acceptis a function defined into the class.

def accept(self):

If you need to pass some parameters to the function you need to store these parameters into some class variables instead passing them as params into the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest