HyperQBE
HyperQBE

Reputation: 97

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.

Upvotes: 3

Views: 2288

Answers (2)

kelvinmacharia254
kelvinmacharia254

Reputation: 167

This can also solve your problem:

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 for '"+str(par_1)+" "+str(par_2)+"'.Would you like to add it to the database")
    

   # 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

Not the use of string concatenation on line 6.

Upvotes: 0

buck54321
buck54321

Reputation: 847

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

Upvotes: 1

Related Questions