How to override QApplication::notify in Qt

Valla picture Valla · Dec 22, 2014 · Viewed 8k times · Source

I am trying to handle exception in my Qt application, I went through a couple of posts which indicated of overriding the QApplication::notify method to handle exceptions in a efficient way in Qt. I am not sure where should I add this overriden method. Is it the mainwindow.h or main.cpp? I added the following function in my MainWindow.h:

bool
notify(QObject * rec, QEvent * ev)
{
  try
  {
    return QApplication::notify(rec,ev);
  }
  catch(Tango::DevFailed & e)
  {
    QMessageBox::warning(0,
                         "error",
                         "error");
  }

  return false;
}

When I build my project I get the following error:

error: cannot call member function 'virtual bool QApplication::notify(QObject*, QEvent*)' without object

I am new to c++ and Qt.Could you let me know how I could implement this so that all my exceptions would be handled in an efficient way and the application does not crash.

Answer

McLeary picture McLeary · Dec 22, 2014

This is a method of a QApplication object. In order to override the notify method you must inherit from QApplication and in your main() you should instantiate a class as the Qt Application

#include <QApplication>
class Application final : public QApplication {
public:
    Application(int& argc, char** argv) : QApplication(argc, argv) {}
    virtual bool notify(QObject *receiver, QEvent *e) override {
         // your code here
    }
};

int main(int argc, char* argv) {
    Application app(argc, argv);
    // Your initialization code
    return app.exec();
}