PyQt5:如何将回溯显示到小部件中?

问题描述

我将错误显示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))

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...