Python PyQt5: How to show an error message with PyQt5

回眸只為那壹抹淺笑 提交于 2019-11-27 22:37:42

问题


In normal Python (3.x) we always use showerror() from the tkinter module to display an error message but what should I do in PyQt5 to display exactly the same message type as well?


回答1:


Qt includes an error-message specific dialog class QErrorMessage which you should use to ensure your dialog matches system standards. To show the dialog just create a dialog object, then call .showMessage(). For example:

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

Here is a minimal working example script:

import PyQt5
from PyQt5 import QtWidgets

app = QtWidgets.QApplication([])

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

app.exec_()



回答2:


Don't forget to call .exec()_ to display the error:

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



回答3:


All above options didn't work for me using Komodo Edit 11.0. Just had returned "1" or if not implemented "-1073741819".

Usefull for me was: Vanloc's solution.

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



回答4:


To show a message box, you can call this def:

from PyQt5.QtWidgets import QMessageBox, QWidget

MainClass(QWidget):
    def __init__(self):
        super().__init__()

    def clickMethod(self):
        QMessageBox.about(self, "Title", "Message")



回答5:


The following should work:

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

It is not the exact same message type (different GUI's) but fairly close. e is the expression for an Error in python3

Hope that helped, Narusan



来源:https://stackoverflow.com/questions/40227047/python-pyqt5-how-to-show-an-error-message-with-pyqt5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!