Search code examples
eventsqtqwidget

QWidget focusOutEvent not received


I've created a date input by subclassing a QLineEdit and a QCalendar. The calender is displayed at the bottom of the QLineEdit when a mousePressEvent is received on it. The problem is with hiding that calendar. I've overridden its focusOutEvent as I want it to be closed when the user clicks somewhere else. But this event is not received at all, I confirmed this by putting a breakpoint in it, it never stops there. I've put a call to close() in it:

class MyCalendarWidget : public QCalendarWidget
{
    Q_OBJECT

public:
    void focusOutEvent(QFocusEvent* e)
    {
        close();
    }
};

When I close it from my DateLineEdit, it works as expected:

void DateLineEdit::mousePressEvent(QMouseEvent *)
{
    if (calendar->isVisible())
    {
        calendar->close();
    }
    else
    {
        calendar->move(mapToGlobal(QPoint(0, height())));
        calendar->show();
    }
}

Solution

  • I'm guessing it's not sending a focusOutEvent because it never had focus in the first place; certainly not if the user subsequently typed something in the DateLineEdit. Capture the focusOutEvent from the DateLineEdit object, and close the calendar at that point; though perhaps you would want to test whether the user clicked on the calendar (in which case it would have focus or at least have received a mousePressEvent) and leave it up in that case (but otherwise close it).