┌   ┐
54
└   ┘

summaryrefslogtreecommitdiff
path: root/src/search/widgetmenu.cpp
blob: 5624e2dfce56dd3d1872ee778fe41ef149847e7c (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
    SPDX-FileCopyrightText: 2025 Felix Ernst <[email protected]>

    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/

#include "widgetmenu.h"

#include <QApplication>
#include <QShowEvent>
#include <QWidgetAction>

using namespace Search;

Search::WidgetMenu::WidgetMenu(QWidget *parent)
    : QMenu{parent}
{
    connect(
        this,
        &QMenu::aboutToShow,
        this,
        [this]() {
            auto widgetAction = new QWidgetAction{this};
            auto widget = init();
            Q_CHECK_PTR(widget);
            widgetAction->setDefaultWidget(widget); // Transfers ownership to the widgetAction.
            addAction(widgetAction);
        },
        Qt::SingleShotConnection);
}

bool WidgetMenu::focusNextPrevChild(bool next)
{
    return QWidget::focusNextPrevChild(next);
}

void WidgetMenu::mouseReleaseEvent(QMouseEvent *event)
{
    return QWidget::mouseReleaseEvent(event);
}

void WidgetMenu::resizeToFitContents()
{
    auto *widgetAction = static_cast<QWidgetAction *>(actions().constFirst());
    auto focusedChildWidget = QApplication::focusWidget();
    if (!widgetAction->defaultWidget()->isAncestorOf(focusedChildWidget)) {
        focusedChildWidget = nullptr;
    }

    // Removing and readding the widget triggers the resize.
    removeAction(widgetAction);
    addAction(widgetAction);

    // The previous removing and readding removed the focus from any child widgets. We return the focus to where it was.
    if (focusedChildWidget) {
        focusedChildWidget->setFocus();
    }
}

void WidgetMenu::showEvent(QShowEvent *event)
{
    if (!event->spontaneous()) {
        auto widgetAction = static_cast<QWidgetAction *>(actions().constFirst());
        widgetAction->defaultWidget()->setFocus();
    }
    QMenu::showEvent(event);
}