CompositeWidgetFocusWatcher.cpp 2.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
    This file is part of Konsole, a terminal emulator for KDE.

    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301  USA.
*/

#include "CompositeWidgetFocusWatcher.h"

#include <QFocusEvent>

using namespace Konsole;

29 30
CompositeWidgetFocusWatcher::CompositeWidgetFocusWatcher(QWidget *compositeWidget)
    : QObject(compositeWidget)
31 32 33 34 35 36 37 38
    , _compositeWidget(compositeWidget)
{
    registerWidgetAndChildren(compositeWidget);
}

bool CompositeWidgetFocusWatcher::eventFilter(QObject *watched, QEvent *event)
{
    switch(event->type()) {
39 40 41 42 43 44
    case QEvent::Close:
    case QEvent::DeferredDelete:
    case QEvent::Destroy:
        removeEventFilter(watched);
        disconnect(this, &CompositeWidgetFocusWatcher::compositeFocusChanged, watched, nullptr);
        break;
45 46 47 48
    case QEvent::FocusIn:
        emit compositeFocusChanged(true);
        break;
    case QEvent::FocusOut:
49
        if(static_cast<QFocusEvent *>(event)->reason() != Qt::PopupFocusReason) {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
            emit compositeFocusChanged(false);
        }
        break;
    default:
        break;
    }
    return false;
}

void CompositeWidgetFocusWatcher::registerWidgetAndChildren(QWidget *widget)
{
    Q_ASSERT(widget != nullptr);

    if (widget->focusPolicy() != Qt::NoFocus) {
        widget->installEventFilter(this);
    }
    for (auto *child: widget->children()) {
        auto *childWidget = qobject_cast<QWidget *>(child);
        if (childWidget != nullptr) {
            registerWidgetAndChildren(childWidget);
        }
    }
}