简体   繁体   English

Qt:如何捕捉QDateEdit点击事件?

[英]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. 我试图通过处理QEvent::MouseButtonRelease事件来捕获QDateEdit小部件上的鼠标单击,但是找不到解决方法。 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. 我尝试覆盖父窗口小部件的QWidget::event方法,但似乎事件会通过子QDateEdit传递给父窗口,而QDateEdit内部处理这些事件而不会传播给父窗口。 Is there any correct solution or workaround? 有没有正确的解决方案或解决方法?

QDateEdit extends a QWidget class. QDateEdit扩展了QWidget类。 So you can just inherit QDateEdit and override virtual void mouseReleaseEvent(QMouseEvent *event) function and do what you want there. 因此,您可以继承QDateEdit并重写virtual void mouseReleaseEvent(QMouseEvent *event)函数,然后在其中执行您想要的操作。

Update: 更新:

Function mouseReleaseEvent is really not invoke. 实际上,不会调用mouseReleaseEvent函数。

Try to install an event filter to the line edit in QDateEdit . 尝试将事件过滤器安装到QDateEdit的行编辑中。 Example: 例:

MyDateEdit.h MyDateEdit.h

#include <QDateEdit>

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

MyDateEdit.cpp 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);
}

One way to do this is to install an eventFilter. 一种方法是安装eventFilter。 The eventFilter section of the Qt documentation provides an example of how it is use. Qt文档的eventFilter部分提供了如何使用它的示例。

Your window class should override eventFilter 您的窗口类应重写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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM