I'm using PyQt5 and I have created a QWidgets with a QpushButton, then connecting button with a function called show_message()
. When I click button the program doesn't work as expected and be crashed with the message: Process finished with exit code -1073741819 (0xC0000005) and without further error information. I have also tried using sys.excepthook
(visit Logging uncaught exceptions in Python ) to log uncaught exception but the result is the same.
Here is my code:
from PyQt5.QtWidgets import QMessageBox, QApplication, QWidget
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QPushButton
import sys
def foo(exctype, value, tb):
print('My Error Information')
print('Type:', exctype)
print('Value:', value)
print('Traceback:', tb)
sys.excepthook = foo
def show_message(title, info, icon_path='ac_solution.ico', type_=QMessageBox.Information):
""" show message """
app = QApplication([])
message_box = QMessageBox()
message_box.setText(info)
message_box.setWindowTitle(title)
message_box.setWindowIcon(QtGui.QIcon(icon_path))
message_box.setIcon(type_)
message_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
message_box.activateWindow()
message_box.show()
app.exec_()
app = QApplication([])
Form = QtWidgets.QWidget(flags=QtCore.Qt.WindowStaysOnTopHint)
button = QPushButton('PyQt5 button', Form)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(lambda: show_message("hahaha", "hehehe"))
Form.show()
try:
app.exec_()
except:
print("exiting")
When I remove lines app = QApplication([])
and app.exec_()
the program will work well, So I can guess QApplication()
in show_message
caused crash. But I don't know why and it makes me curious, so I need an explaination.
There are two main issues with your code. First, you are trying to run a second instance of QApplication
in show_message
which is what's causing the crash. Secondly, message_box
is local to show_message
meaning that when message_box
finishes, show_message
is destroyed. One way around this is to create the message box outside the function and supply it as an input parameter, e.g.
def show_message(message_box, title, info, icon_path='ac_solution.ico', type_=QMessageBox.Information):
""" show message """
message_box.setText(info)
message_box.setWindowTitle(title)
message_box.setWindowIcon(QtGui.QIcon(icon_path))
message_box.setIcon(type_)
message_box.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
message_box.activateWindow()
message_box.show()
...
button.clicked.connect(lambda x, box = QMessageBox(): show_message(box, "hahaha", "hehehe"))