tags:

views:

328

answers:

5

Hey, this may seem like a very simple question, but I want to dump some data whenever the QMainWindow closes, so I used the following piece of code:

QObject::connect(MainWindow.centralwidget, SIGNAL(destroyed()), this, SLOT(close()));

but this doesnt seem to make it call close(). Am I doing this wrong? Isnt the centralwidget suppose to be destroyed? Or perhaps the application closes before close() can be called? Any other ways of doing it then?

Thanks in advance!

+2  A: 

Could you implement the closeEvent function for your QMainWindow and put your code there?

Bill
+1  A: 

Your initial question and code don't match. If you want to do something on the QMainWindow either create a sub-class and re-implement closeEvent or connect to MainWindow::destroyed(). See the 3rd paragraph for a note however.

But your code is showing what appears to be a 3rd class that is connecting a child of the MainWindow being destroyed to some slot called close(). centralwidget will be destroyed AFTER MainWindow is already destroyed so this most likely won't help you anyway.

Also, this depends on how you created MainWindow (stack or heap) and if you are destructing it properly. Ideally, you should create a subclass of QMainWindow (which if you used the designer you probably already have).

Adam W
+1  A: 

You better to re implement one virtual function in your main MainWindow class like this:

class MainWindow : public QMainWindow {

    Q_OBJECT;

public:
    MainWindow();

protected:
     void closeEvent(QCloseEvent *event);
}

and then declare in source file:

void MainWindow::closeEvent(QCloseEvent *event) {
     // do some data saves or something else
}

Good luck.

mosg
+7  A: 

I'd try QApplication::lastWindowClosed() instead.

Jurily
Didn't work, must mean it's being destroyed before that signal can be accepted? But that's odd because the class's destructor doesn't seem to be outputting anything (through std::cerr)
Cenoc
Make sure the object with the slot isn't a child of the QMainWindow. QWidgets destroy all their children when they go down.
Jurily
@Cenoc: Post your `main` function, it can help clear up what is going on.
Adam W
Woops, good catch, it worked! A million thanks! Definitely wouldnt have looked in the QApplication for this.
Cenoc
A: 

How about adding the dump code to your main windows' destructor?

Rob
Tried that, it doesnt output.... odd?
Cenoc
You can't accesss I/O in destroyed or the destructor of the MainWindow - you are finally in your applications destructor and everything is destroyed. Use closeEvent() instead.
Jens