问题描述
我将错误显示到 QPlainTextEdit
或任何其他更合适的小部件中。
code.py:
import traceback
from PyQt5 import QtCore,QtGui,QtWidgets
class Ui_MainWindow(object):
def setupUi(self,MainWindow):
MainWindow.setobjectName("MainWindow")
MainWindow.resize(394,185)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setobjectName("centralwidget")
self.plntxt = QtWidgets.QPlainTextEdit(self.centralwidget)
self.plntxt.setGeometry(QtCore.QRect(10,10,371,131))
self.plntxt.setobjectName("plntxt")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setobjectName("statusbar")
self.m()
def m(self):
try:
sdhfha #to create error that will be displayed to GUI
except Exception as a:
#I'm trying to pass the error named a into the PlainTextEdit
self.plntxt.setPlainText(a)
pass
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
错误是:
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "C:\Users\???\AppData\Local\Programs\Python\python38\Lib\site-packages\pyside2\???...
TypeError: setPlainText(self,str): argument 1 has unexpected type 'NameError'
[Finished in 0.4s]
有什么想法吗?
解决方法
您必须将异常转换为字符串:
def m(self):
try:
sdhfha
except Exception as a:
self.plntxt.setPlainText(str(a))
,
嘿,这也有效:
self.plntxt.append(str(a))