while write data to QTextEdit, when close window, it show error

0

i am write a pyqt5 demo while write data to QTextEdit in a timer event, when close window, it show error

from PyQt5.QtSerialPort import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.msgTE = QTextEdit()
        self.msgTE.setReadOnly(True)


        layout = QGridLayout()
        layout.addWidget(self.msgTE, 0, 0, 1, 2)


        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.startTimer(10)



    def timerEvent(self, *event):
        QApplication.processEvents()
        self.msgTE.insertPlainText('12')


    def closeEvent(self, *args, **kwargs):
        self.killTimer()


app = QApplication(sys.argv)
demo = MainWindow()
demo.show()
app.exec()

** The output: Process finished with exit code -1073740791 (0xC0000409)**

python
pyqt
pyqt5
qtextedit
asked on Stack Overflow Jul 17, 2019 by jett • edited Jul 17, 2019 by Vadim Kotov

1 Answer

1

I recommend executing the script in the terminal/CMD since many IDEs do not handle the Qt exceptions, if you do then you should obtain the following:

Traceback (most recent call last):
  File "main.py", line 34, in closeEvent
    self.killTimer()
TypeError: killTimer(self, int): not enough arguments

That tells us that killTimer() expects an argument, in this case it is the id associated with the timer since you can start several timers and you only want to stop one, that id is to return by the startTimer() method.

Considering the above the solution is:

from PyQt5 import QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.msgTE = QtWidgets.QTextEdit(readOnly=True)

        widget = QtWidgets.QWidget()

        layout = QtWidgets.QGridLayout(widget)
        layout.addWidget(self.msgTE, 0, 0)

        self.setCentralWidget(widget)

        self.m_timer_id = self.startTimer(10)

    def timerEvent(self, event):
        if event.timerId() == self.m_timer_id:
            self.msgTE.insertPlainText("12")
        super().timerEvent(event)

    def closeEvent(self, event):
        self.killTimer(self.m_timer_id)
        super().closeEvent(event)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    demo = MainWindow()
    demo.show()
    sys.exit(app.exec())
answered on Stack Overflow Jul 17, 2019 by eyllanesc • edited Jul 17, 2019 by eyllanesc

User contributions licensed under CC BY-SA 3.0