【问题标题】:Python PyQt5: How to show an error message with PyQt5Python PyQt5:如何使用 PyQt5 显示错误消息
【发布时间】:2017-03-06 17:45:48
【问题描述】:

在普通的 Python (3.x) 中,我们总是使用 tkinter 模块中的 showerror() 来显示错误消息,但是在 PyQt5 中我应该怎么做才能显示完全相同的消息类型呢?

【问题讨论】:

    标签: python message messagebox pyqt5


    【解决方案1】:

    别忘了调用.exec_()来显示错误:

    from PyQt5.QtWidgets import QMessageBox
    
    msg = QMessageBox()
    msg.setIcon(QMessageBox.Critical)
    msg.setText("Error")
    msg.setInformativeText('More information')
    msg.setWindowTitle("Error")
    msg.exec_()
    

    【讨论】:

    • 感谢.exec_() 的提示!
    • 完美运行。谢谢!
    【解决方案2】:

    Qt 包含一个error-message specific dialog classQErrorMessage,您应该使用它来确保您的对话符合系统标准。要显示对话框,只需创建一个对话框对象,然后调用.showMessage()。例如:

    error_dialog = QtWidgets.QErrorMessage()
    error_dialog.showMessage('Oh no!')
    

    这是一个最小的工作示例脚本:

    import PyQt5
    from PyQt5 import QtWidgets
    
    app = QtWidgets.QApplication([])
    
    error_dialog = QtWidgets.QErrorMessage()
    error_dialog.showMessage('Oh no!')
    
    app.exec_()
    

    【讨论】:

      【解决方案3】:

      要显示一个消息框,你可以调用这个def:

      from PyQt5.QtWidgets import QMessageBox, QWidget
      
      MainClass(QWidget):
          def __init__(self):
              super().__init__()
      
          def clickMethod(self):
              QMessageBox.about(self, "Title", "Message")
      

      【讨论】:

        【解决方案4】:

        以上所有选项都不适用于我使用 Komodo Edit 11.0。刚刚返回“1”或者如果没有实现“-1073741819”。

        对我有用的是:Vanloc's 解决方案。

        def my_exception_hook(exctype, value, traceback):
            # Print the error and traceback
            print(exctype, value, traceback)
            # Call the normal Exception hook after
            sys._excepthook(exctype, value, traceback)
            sys.exit(1)
        
        # Back up the reference to the exceptionhook
        sys._excepthook = sys.excepthook
        
        # Set the exception hook to our wrapping function
        sys.excepthook = my_exception_hook
        

        【讨论】:

          【解决方案5】:

          以下应该有效:

          msg = QMessageBox()
          msg.setIcon(QMessageBox.Critical)
          msg.setText("Error")
          msg.setInformativeText(e)
          msg.setWindowTitle("Error")
          

          它不是完全相同的消息类型(不同的 GUI),但相当接近。 e 是 python3 中错误的表达式

          希望有所帮助, 鸣山

          【讨论】:

          • 你应该写一个数字作为参数,而不是 msg.setIcon(QMessageBox.critical)。见:doc.qt.io/qt-5/qmessagebox.html#Icon-enum
          • @AlanHorman。不,这只是一个错字 - 应该是 QMessageBox.Critical(即大写“C”)。
          • 抱歉打错字了,我应该仔细检查拼写
          【解决方案6】:

          假设你在一个 QWidget 中,你想从中显示错误消息,你可以简单地使用 QMessageBox.critical(self, "Title", "Message"),如果你不是 QWidget 类,则将 self 替换为另一个(例如主小部件)。

          【讨论】:

            猜你喜欢
            • 2017-08-19
            • 1970-01-01
            • 1970-01-01
            • 2018-12-16
            • 2015-10-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-07
            相关资源
            最近更新 更多