rugby82
rugby82

Reputation: 699

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??

Upvotes: 7

Views: 28447

Answers (2)

ekhumoro
ekhumoro

Reputation: 120808

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))

Upvotes: 19

Nicola
Nicola

Reputation: 231

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.

Upvotes: 6

Related Questions