繁体   English   中英

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

[英]PyQt5: How to display traceback(s) into a Widget?

我将错误显示到QPlainTextEdit更适合的任何其他小部件中。

代码.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))
我谦虚的方法是:格式化字符串文字-> f {}
self.plntxt.setPlainText(f'{a}')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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