When I close a window which has a logger and then re-open the window, I get “RuntimeError: Internal C++ object (PySide6.QtWidgets.QPlainTextEdit) already deleted.”(I made the logger based off of this post: Best way to display logs in pyqt?).
When I remove “self.deleteLater()” from LoggerWindow’s closeEvent, I don’t get the error since QWidget is not deleted. But the problem is that in my program, I need “self.deleteLater()” to detect that the window is closed (using self.(QWidget).destroyed.connect()).
Is there any way to avoid this error, or is there a different way to detect when a window closes?
from PySide6.QtWidgets import QApplication, QWidget, QPlainTextEdit, QVBoxLayout, QPushButton
import os
import logging
import sys
class QTextEditLogger(logging.Handler):
def __init__(self, parent):
super().__init__()
self.widget = QPlainTextEdit(parent)
self.widget.setReadOnly(True)
def emit(self, record):
msg = self.format(record)
self.widget.appendPlainText(msg)
class LoggerWindow(QWidget):
parent_dir = os.getcwd()
def __init__(self):
super().__init__()
self.logger_text_edit = QTextEditLogger(self)
self.logger_text_edit.setFormatter(logging.Formatter('[%(asctime)s %(levelname)s]: %(message)s'))
logging.getLogger().addHandler(self.logger_text_edit)
logging.getLogger().setLevel(logging.DEBUG)
logging.info("Initialized")
main_v_layout = QVBoxLayout()
main_v_layout.addWidget(self.logger_text_edit.widget)
self.setLayout(main_v_layout)
def closeEvent(self, event):
self.deleteLater()
class MainWindow(QWidget):
def __init__(self, app):
super().__init__()
main_v_layout = QVBoxLayout()
button = QPushButton("Push!")
main_v_layout.addWidget(button)
self.setLayout(main_v_layout)
button.clicked.connect(self.button_clicked)
def button_clicked(self):
self.logger_window = LoggerWindow()
self.logger_window.show()
app = QApplication(sys.argv)
window = MainWindow(app)
window.show()
app.exec()
HK51503 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.