vowchick
vowchick

Reputation: 11

How can i stop QT Widget from closing?

I have a class (Window) that inherits from QWidget (Not QMainWindow). This is the important part of my main function.

 QApplication app (argc, argv);

 QMainWindow *window = new QMainWindow;

 QMenuBar *tool_bar = new QMenuBar (window);

 Window *graph_area = new Window (arguments);

 window->setMenuBar (tool_bar);
 window->setCentralWidget (graph_area);
 window->show ();
 app.exec ();

I thought that i would just override "closeEvent", but for some reason it doesn't get called when pressing the closing button.

I want to stop the user from closing the application if some process is still working.

Any ideas about how i might achieve that?

Upvotes: 1

Views: 1067

Answers (3)

vowchick
vowchick

Reputation: 11

I actually found another solution to my problem, that I find more pleasant. I can create a custom class mainwindow that inherits from QMainWindow and use it instead of QMainWindow. It might be more appropriate, because I will probably need some other changes to QMainWindow as well.

Upvotes: -1

Make your Window class an event filter and install it on the main window object. You’ll reimplement filterEvent method in Window. Do not forget to install it on the main window! And make sure that the filter filters the event out - the boolean result indicates whether you let the result through or filter it out. Look up the exact value needed to indicate either one - it’s a bad api and I never remember whether true or false does what I intend. It’s a classical case where an enumeration return value would work better, like Qt::Accept/Qt::Reject or some such.

Upvotes: 1

scopchanov
scopchanov

Reputation: 8419

You can either:

  1. Subclass QMainWindow, instead of QWidget

  2. Override QMainWindow::closeEvent, instead of QWidget::closeEvent

  3. Allocate your QMainWindow subclass on the stack, instead of on the heap, i.e.:

     MyMainWindowSubclass window;
    

or:

Change your code to:

QApplication app(argc, argv);

Window w;

window->show();

app.exec();

and Window::closeEvent will be called.

Upvotes: 1

Related Questions