Search code examples
c++qtqt5qpushbutton

application wide logging when any QPushButton being pressed


Suppose I have an application that is made using Qt. There I have a bunch of QPushBUttons here and there.

I want to be able to log the moment when any of QPushButton being pressed. (application wide). Assuming the existing code should be intact, What will be the best option for that?

( Derive from QPushButton and re-implementing keyPressEvent is not a solution because client code will be changed and will be obligatory to use other class rather than ordinary QPushButton )


Solution

  • According to what you point out, you want to know when a button is pressed, which in general is when the QEvent::MouseButtonPress event is sent to a QPushButton, and for this you must overwrite the notify method of QApplication

    #include <QtWidgets>
    
    class LoggerApplication: public QApplication
    {
    public:
        using QApplication::QApplication;
    public:
        bool notify(QObject *receiver, QEvent *event){
            if(QPushButton *button = qobject_cast<QPushButton *>(receiver))
                if(event->type() == QEvent::MouseButtonPress)
                    qDebug()<< button->text();
            return QApplication::notify(receiver, event);
        }
    };
    
    int main(int argc, char *argv[])
    {
        LoggerApplication a(argc, argv);
        QWidget w;
        QGridLayout *lay = new QGridLayout{&w};
        for(int i=0; i<5; ++i)
            for(int j=0; j<5; ++j)
                lay->addWidget(new QPushButton(QString("%1-%2").arg(i).arg(j)), i, j);
        w.show();
        return a.exec();
    }