Search code examples
c++qtclickqwidgetqevent

Qt: How to catch QDateEdit click event?


I'm trying to catch mouse click on QDateEdit widget by handling QEvent::MouseButtonRelease event, but can't find a way to do it. I tried to override QWidget::event method of the parent widget, but it seems that events go through children to parent, and QDateEdit internally handles those events without propagating to a parent. Is there any correct solution or workaround?


Solution

  • QDateEdit extends a QWidget class. So you can just inherit QDateEdit and override virtual void mouseReleaseEvent(QMouseEvent *event) function and do what you want there.

    Update:

    Function mouseReleaseEvent is really not invoke.

    Try to install an event filter to the line edit in QDateEdit. Example:

    MyDateEdit.h

    #include <QDateEdit>
    
    class MyDateEdit : public QDateEdit
    {
      Q_OBJECT
    public:
      MyDateEdit(QWidget *parent = 0);
      bool eventFilter(QObject* object, QEvent* event) override;
    };
    

    MyDateEdit.cpp

    #include "MyDateEdit.h"    
    #include <QDebug>
    #include <QEvent>
    #include <QLineEdit>
    
    MyDateEdit::MyDateEdit(QWidget *parent) : QDateEdit (parent)
    {
      installEventFilter(this);
      lineEdit()->installEventFilter(this);
    }
    
    bool MyDateEdit::eventFilter(QObject* object, QEvent* event)
    {
      if (object == this || object == lineEdit())
      {
        if (event->type() == QEvent::MouseButtonRelease)
        {
          qDebug() << "Mouse release event";
        }
      }    
      return QDateEdit::eventFilter(object, event);
    }