[SOLVED] How does delete works for QTimer


Although QTimer inherits QObject which we don’t need to delete it manually, is that ok to put it in a method which will be called multiple time?

void MainWindow::paintEvent(QPaintEvent *event) {
    //create a timer to update every frame
    QTimer* timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(next_frame()));

    QPainter painter(this);
    render(painter, counter);

    //if the game is not paused, increase the counter
    if (isPlaying) counter++;


While QObjects are deleted automatically if they have a parent, they are only deleted when the parent is deleted. You are in your case making new QTimers and leaving them as a dead-weight hanging off their parent objects, this essentially a memory leak, and a sneaky one memory-leak checking tools can’t even find as the object is still referenced by their parent. You should deleted QObjects when you are no longer using them, though if you are in somekind of slot or callback from something they did use QObject::deleteLater().

Though in this case as someone already said, don’t use a QTimer object, but a single-shot timer, or alternatively a QBasicTimer.

Answered By – Allan Jensen

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *