Search code examples
pythonuser-interfacepyqtqmessagebox

How to use variable in pyqt MessageBox


I'm using MessageBox to get user input if data is to be added to database, but I don't know how to place my variables inside the actual message. MessageBox function looks like this:

def message(self, par_1, par_2):
    odp = QMessageBox.question(self, 'Information', "No entry. Would you like to add it to DB?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
    if odp == QMessageBox.Yes:
        return True
    else:
        return False

Function is called like this:

self.message(autor_firstname, autor_lastname)

I tried adding:

odp.setDetailText(par_1, par_2)

But it didn't work as expected. Additionally I have problem when user clicks "No". Program crashes instead of returning to main window.


Solution

  • As per the docs on QMessageBox::question, the return value is the button that was clicked. Using the static method QMessageBox::question limits how you can customize the QMessageBox. Instead, create an instance of QMessageBox explicitly, call setText, setInformativeText, and setDetailedText as needed. Note that your arguments also do not match what is needed for setDetailedText. Those docs are here. I think your code should look something like this.

    def message(self, par_1, par_2):
    
        # Create the dialog without running it yet
        msgBox = QMessageBox()
    
        # Set the various texts
        msgBox.setWindowTitle("Information")
        msgBox.setText("No entry. Would you like to add it to the database")
        detail = "%s\n%s" % (par_1, par_2) # formats the string with one par_ per line.
        msgBox.setDetailedText(detail) 
    
        # Add buttons and set default
        msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        msgBox.setDefaultButton(QMessageBox.No)     
    
        # Run the dialog, and check results   
        bttn = msgBox.exec_()
        if bttn == QMessageBox.Yes:
            return True
        else:
            return False