qtquit

Using the closeEvent in a qt application does not close it


I am learning qt, and experimenting with examples from a textbook.

The original textbook code has the following, set up to save and close on the x button:

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (okToContinue()) {
        writeSettings();
        event->accept();
    } else {
        event->ignore();
    }
}

i experimented with a simple exit in its menu - and it works:

void MainWindow::close()
{
    if (okToContinue()) {
        QApplication::quit();
    }
}

But I want to take advantage of the already written closeEvent, so i replaced the code above with

void MainWindow::close()
{
    QCloseEvent *event = new QCloseEvent();
    closeEvent(event);
}

I get the checking for changes and saving app, implemented through the okToContinue function. But the application does not close.

i tried to follow through debugging and.. with my small understanding, it seems that there is a close signal being sent...

I don't have a good understanding of this, can somebody please help me figure out what am i doing wrong and how to fix it ?

(the sample code is from C++ GUI Programming with Qt 4, chapter 3)


Solution

  • You don't have to reimplement MainWindow::close() in your subclass. From the Qt Docs:

    ...QCloseEvent sent when you call QWidget::close() to close a widget programmatically...

    So you just have to reimplement MainWindow::closeEvent(QCloseEvent *event) if you want to control this event.

    This event fires when you click x or call close() from the code.