Denis
Denis

Reputation: 3092

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?

Upvotes: 0

Views: 1421

Answers (2)

Alexander Trotsenko
Alexander Trotsenko

Reputation: 504

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

Upvotes: 2

zeFrenchy
zeFrenchy

Reputation: 6591

One way to do this is to install an eventFilter. The eventFilter section of the Qt documentation provides an example of how it is use.

Your window class should override eventFilter

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
  if (obj == dateEdit) {
    if (event->type() == QEvent::MouseButtonPress) {
        // do what you want to do
        // alternatively use QEvent::MouseButtonRelease 
        return true;
    } else {
        return false;
    }
  } else {
    // pass the event on to the parent class
    return QMainWindow::eventFilter(obj, event);
  }
}

In your window constructor, install the filter on the actual widget:

dateEdit->installEventFilter(this);

Upvotes: 1

Related Questions