简体   繁体   中英

Python PyQt5: How to show an error message with PyQt5

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

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

from PyQt5.QtWidgets import QMessageBox

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

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_()

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

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")

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM