jett chen
jett chen

Reputation: 1173

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

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)**

Upvotes: 0

Views: 209

Answers (1)

eyllanesc
eyllanesc

Reputation: 244172

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())

Upvotes: 1

Related Questions