Search code examples
qteventfilterqcalendarwidget

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


I used event filter on my QDateEdit 'sdateEdit' as follows:

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

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

But this doesnt work. I tried .. sdateEdit->setCalendarPopup(true). This did not work as well.


Solution

  • In this case I have implemented a custom QDateEdit, the strategy is to use eventFilter when you click on the QLineEdit and send a click event to the arrow:

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