How to override QApplication::notify in Qt

℡╲_俬逩灬. 提交于 2019-12-05 02:29:47

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();
}

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

That error message is trying to write that you are trying to call a non-static method without an actual object. Only static methods could work like that. Even if it was intended like that, which it is not, it could not be a static method anyway as C++ does not support virtual static methods (sadly, but that is another topic).

Therefore, I would personally do something like this:

main.cpp

#include <QApplication>
#include <QEvent>
#include <QDebug>

class MyApplication Q_DECL_FINAL : public QApplication
{
    Q_OBJECT
public:
    MyApplication(int &argc, char **argv) : QApplication(argc, argv) {}

    bool notify(QObject* receiver, QEvent* event) Q_DECL_OVERRIDE
    {
        try {
            return QApplication::notify(receiver, event);
        //} catch (Tango::DevFailed &e) {
            // Handle the desired exception type
        } catch (...) {
            // Handle the rest
        }        

         return false;
     }
};

#include "main.moc"

int main(int argc, char **argv)
{
    MyApplication application(argc, argv);
    qDebug() << "QApplication::notify example running...";
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT += widgets
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Just like with other event handlers in Qt, you need to define a child class derived from QApplication and implement bool notify (QObject *receiver, QEvent *e) there, then use your class instead of QApplication.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!