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

Posted

技术标签:

【中文标题】PyQt5:如何将回溯显示到小部件中?【英文标题】:PyQt5: How to display traceback(s) into a Widget? 【发布时间】:2021-01-19 06:55:24 【问题描述】:

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

有什么想法吗?

【问题讨论】:

【参考方案1】:

您必须将异常转换为字符串:

def m(self):
    try:
        sdhfha
    except Exception as a:
        self.plntxt.setPlainText(str(a))

【讨论】:

以上是关于PyQt5:如何将回溯显示到小部件中?的主要内容,如果未能解决你的问题,请参考以下文章

如何将图像从 Firebase 存储显示到小部件中?

如何在PyQt5中叠加小部件?

小部件未在 pyqt5 中显示标签

将数据从 Flutter Stream 传递到小部件

iOS将按钮添加到小部件扩展

在pyqt5中的QWidget上实现dragMoveEvent?