QDateEdit 的弹出式日历小部件在文本区域的任何地方单击鼠标,而不仅仅是向下箭头,

Pop-up calendar widget of QDateEdit on mouseclick anywhere in text area and not just the down arrow,

我在 QDateEdit 'sdateEdit' 上使用了事件过滤器,如下所示:

bool Class::eventFilter ( QObject *obj, QEvent *event )
{
    if(event->type() == QEvent::MouseButtonPress)
    {      
        sdateEdit->calendarWidget()->show();

    }
    else
        return QObject::eventFilter ( obj, event );
}

但这不起作用。 我试过 .. sdateEdit->setCalendarPopup(true)。这也不起作用。

在这种情况下,我实现了一个自定义 QDateEdit,策略是当您单击 QLineEdit 时使用 eventFilter 并向箭头发送单击事件:

#include <QtWidgets>

class DateEdit: public QDateEdit
{
public:
    DateEdit(QWidget *parent=nullptr):
        QDateEdit(parent)
    {
       lineEdit()->installEventFilter(this);
    }
    bool eventFilter(QObject *watched, QEvent *event) override
    {
        if(watched == lineEdit() && event->type() == QEvent::MouseButtonPress){
            QStyleOptionComboBox opt;
            opt.init(this);
            QRect r = style()->subControlRect(QStyle::CC_ComboBox, &opt, QStyle::SC_ComboBoxArrow, this);
            QPoint p = r.center();
            QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress, p, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
            QCoreApplication::sendEvent(this, event);
        }
        return QDateEdit::eventFilter(watched, event);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DateEdit w;
    w.setCalendarPopup(true);
    w.show();
    return a.exec();
}