]> cloud.milkyroute.net Git - dolphin.git/blob - src/search/widgetmenu.cpp
Clazy fix
[dolphin.git] / src / search / widgetmenu.cpp
1 /*
2 SPDX-FileCopyrightText: 2025 Felix Ernst <felixernst@kde.org>
3
4 SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
5 */
6
7 #include "widgetmenu.h"
8
9 #include <QApplication>
10 #include <QShowEvent>
11 #include <QWidgetAction>
12
13 using namespace Search;
14
15 Search::WidgetMenu::WidgetMenu(QWidget *parent)
16 : QMenu{parent}
17 {
18 connect(
19 this,
20 &QMenu::aboutToShow,
21 this,
22 [this]() {
23 auto widgetAction = new QWidgetAction{this};
24 auto widget = init();
25 Q_CHECK_PTR(widget);
26 widgetAction->setDefaultWidget(widget); // Transfers ownership to the widgetAction.
27 addAction(widgetAction);
28 },
29 Qt::SingleShotConnection);
30 }
31
32 bool WidgetMenu::focusNextPrevChild(bool next)
33 {
34 return QWidget::focusNextPrevChild(next);
35 }
36
37 void WidgetMenu::mouseReleaseEvent(QMouseEvent *event)
38 {
39 return QWidget::mouseReleaseEvent(event);
40 }
41
42 void WidgetMenu::resizeToFitContents()
43 {
44 auto *widgetAction = static_cast<QWidgetAction *>(actions().constFirst());
45 auto focusedChildWidget = QApplication::focusWidget();
46 if (!widgetAction->defaultWidget()->isAncestorOf(focusedChildWidget)) {
47 focusedChildWidget = nullptr;
48 }
49
50 // Removing and readding the widget triggers the resize.
51 removeAction(widgetAction);
52 addAction(widgetAction);
53
54 // The previous removing and readding removed the focus from any child widgets. We return the focus to where it was.
55 if (focusedChildWidget) {
56 focusedChildWidget->setFocus();
57 }
58 }
59
60 void WidgetMenu::showEvent(QShowEvent *event)
61 {
62 if (!event->spontaneous()) {
63 auto widgetAction = static_cast<QWidgetAction *>(actions().constFirst());
64 widgetAction->defaultWidget()->setFocus();
65 }
66 QMenu::showEvent(event);
67 }