简体   繁体   中英

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()));
    timer->start();

    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.

Use QTimer::singleShot(100, this, SLOT(next_frame())); instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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