代码之家  ›  专栏  ›  技术社区  ›  HyperQBE

如何在pyqt MessageBox中使用变量

  •  2
  • HyperQBE  · 技术社区  · 7 年前

    如果要将数据添加到数据库中,我使用MessageBox获取用户输入,但我不知道如何将变量放入实际消息中。MessageBox函数如下所示:

    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
    

    函数的调用方式如下:

    self.message(autor_firstname, autor_lastname)
    

    我试着加上:

    odp.setDetailText(par_1, par_2)
    

    但它并没有像预期的那样起作用。此外,当用户单击“否”时,我会遇到问题。程序崩溃,而不是返回主窗口。

    2 回复  |  直到 7 年前
        1
  •  1
  •   buck54321    7 年前

    根据 the docs on QMessageBox::question ,返回值是单击的按钮。使用静态方法 QMessageBox::question 限制了如何自定义 QMessageBox .而是创建一个 QMessageBox 明确地说,打电话 setText , setInformativeText setDetailedText 根据需要。请注意,您的论点也不符合 setDetailedText .那些文件是 here .我觉得你的代码应该是这样的。

    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
    
        2
  •  0
  •   kelvinmacharia254    5 年前

    这也可以解决你的问题:

    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
    

    而不是在第6行使用字符串连接。