Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt QDialog return response yes or no

Tags:

python

pyqt

I have a QDialog class

confirmation_dialog = uic.loadUiType("ui\\confirmation_dialog.ui")[0]

class ConfirmationDialog(QDialog,confirmation_dialog):

    def __init__(self,parent=None):
        QDialog.__init__(self,parent)
        self.setupUi(self)
        message = "Hello, Dialog test"
        self.yes_button.clicked.connect(self.yes_clicked)
        self.no_button.clicked.connect(self.no_clicked)
        self.message_box.insertPlainText(message)

    def yes_clicked(self):
        self.emit(SIGNAL("dialog_response"),"yes")

    def no_clicked(self):
        self.emit(SIGNAL("dialog_response"),"no")

I have a function which requires confirmation to continue or not, but with the current implementation it doesn't wait for QDialog to close.

How can I make my function wait for response from QDialog and then proceed accordingly.

I want to implement something similar to confirm function as shown below

def function(self):
    ....
    ....
    if self.confirm() == 'yes':
        #do something
    elif self.confirm() == 'no':
        #do something

def confirm(self):
    dialog = ConfirmationDialog()
    dialog.show()
    return #response from dialog
like image 625
Harwee Avatar asked May 24 '16 11:05

Harwee


1 Answers

You would use dialog.exec_(), which will open the dialog in a modal, blocking mode and returns an integer that indicates whether the dialog was accepted or not. Generally, instead of emitting signals, you probably just want to call self.accept() or self.reject() inside the dialog to close it.

dialog = ConfirmationDialog()
result = dialog.exec_()
if result:  # accepted
    return 'accepted'

If I'm using a dialog to get a specific set of values from the user, I'll usually wrap it in a staticmethod, that way I can just call it and get values back within the control flow of my application, just like a normal function.

class MyDialog(...)

    def getValues(self):
        return (self.textedit.text(), self.combobox.currentText())

    @staticmethod
    def launch(parent):
        dlg = MyDialog(parent)
        r = dlg.exec_()
        if r:
            return dlg.getValues()
        return None

values = MyDialog.launch(None)

However, in almost all cases where I just need to present a message to the user, or get them to make a choice by clicking a button, or I need them to input a small piece of data, I can use the built-in static methods on the normal dialog classes -- QMessageBox, QInputDialog

like image 179
Brendan Abel Avatar answered Oct 14 '22 01:10

Brendan Abel