Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquickmenu.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qquickmenu_p.h"
8#include <private/qtquicktemplates2-config_p.h>
9#if QT_CONFIG(quicktemplates2_container)
10#include "qquickmenubaritem_p.h"
11#include "qquickmenubar_p_p.h"
12#endif
19#include "qquickaction_p.h"
20
21#include <QtCore/qloggingcategory.h>
22#include <QtGui/qevent.h>
23#include <QtGui/qcursor.h>
24#if QT_CONFIG(shortcut)
25#include <QtGui/qkeysequence.h>
26#endif
27#include <QtGui/qpa/qplatformintegration.h>
28#include <QtGui/qpa/qplatformtheme.h>
29#include <QtGui/private/qhighdpiscaling_p.h>
30#include <QtGui/private/qguiapplication_p.h>
31#include <QtQml/qqmlcontext.h>
32#include <QtQml/qqmlcomponent.h>
33#include <QtQml/private/qqmlengine_p.h>
34#include <QtQml/private/qqmldata_p.h>
35#include <QtQml/private/qv4scopedvalue_p.h>
36#include <QtQml/private/qv4variantobject_p.h>
37#include <QtQml/private/qv4qobjectwrapper_p.h>
38#include <private/qqmlobjectmodel_p.h>
39#include <QtQuick/private/qquickitem_p.h>
40#include <QtQuick/private/qquickitemchangelistener_p.h>
41#include <QtQuick/private/qquickitemview_p_p.h>
42#include <QtQuick/private/qquickevents_p_p.h>
43#include <QtQuick/private/qquicklistview_p.h>
44#include <QtQuick/private/qquickrendercontrol_p.h>
45#include <QtQuick/private/qquickwindow_p.h>
46
48
49Q_STATIC_LOGGING_CATEGORY(lcMenu, "qt.quick.controls.menu")
50Q_STATIC_LOGGING_CATEGORY(lcNativeMenus, "qt.quick.controls.nativemenus")
51
52// copied from qfusionstyle.cpp
53static const int SUBMENU_DELAY = 225;
54
55/*!
56 \qmltype Menu
57 \inherits Popup
58//! \nativetype QQuickMenu
59 \inqmlmodule QtQuick.Controls
60 \since 5.7
61 \ingroup qtquickcontrols-menus
62 \ingroup qtquickcontrols-popups
63 \brief Menu popup that can be used as a context menu or popup menu.
64
65 \table
66 \row
67 \li \image qtquickcontrols-menu-native.png
68 {Menu with New, Open, Save in native style}
69 \caption Native macOS menu.
70 \li \image qtquickcontrols-menu.png
71 {Menu with New, Open, Save in Material style}
72 \caption Non-native \l {Material Style}{Material style} menu.
73 \endtable
74
75 Menu has two main use cases:
76 \list
77 \li Context menus; for example, a menu that is shown after right clicking
78 \li Popup menus; for example, a menu that is shown after clicking a button
79 \endlist
80
81 For context menus, see \l {Context Menus}.
82
83 When used as a popup menu, it is easiest to specify the position by specifying
84 the desired \l {Popup::}{x} and \l {Popup::}{y} coordinates using the respective
85 properties, and call \l {Popup::}{open()} to open the menu.
86
87 \snippet qtquickcontrols-menu-button-menu.qml root
88
89 If the button should also close the menu when clicked, use the
90 \c Popup.CloseOnPressOutsideParent flag:
91
92 \snippet qtquickcontrols-menu-closepolicy.qml closePolicy
93
94 You can create sub-menus and declare Action objects inside Menu:
95
96 \snippet qtquickcontrols-menu-submenus-and-actions.qml root
97
98 Sub-menus are \l {cascade}{cascading} by default on desktop platforms
99 that have a mouse cursor available. Non-cascading menus are shown one
100 menu at a time, and centered over the parent menu.
101
102 Typically, menu items are statically declared as children of the menu, but
103 Menu also provides API to \l {addItem}{add}, \l {insertItem}{insert},
104 \l {moveItem}{move} and \l {removeItem}{remove} items dynamically. The
105 items in a menu can be accessed using \l itemAt() or
106 \l {Popup::}{contentChildren}.
107
108 Although \l {MenuItem}{MenuItems} are most commonly used with Menu, it can
109 contain any type of item.
110
111 \section1 Context Menus
112
113 For context menus, it is easier to use the \l ContextMenu attached type,
114 which creates a menu upon a platform-specific event. In addition, text
115 editing controls such as \l TextField, \l TextArea, \l SpinBox, and
116 \l DoubleSpinBox provide their own context menus by default.
117
118 If not using \c ContextMenu, the recommended way of opening the menu is to
119 call \l popup(). Unless a position is explicitly specified, the menu is
120 positioned at the mouse cursor on desktop platforms that have a mouse
121 cursor available, and otherwise centered over its parent item:
122
123 \snippet qtquickcontrols-menu-contextmenu.qml children
124
125 Note that if you are implementing your own context menu for text editing
126 controls, you only need to show it on desktop platforms, as iOS and Android
127 have their own native context menus:
128
129 \snippet qtquickcontrols-menu-text-editing-contextmenu.qml children
130
131 \section1 Margins
132
133 As it is inherited from Popup, Menu supports \l {Popup::}{margins}. By
134 default, all of the built-in styles specify \c 0 for Menu's margins to
135 ensure that the menu is kept within the bounds of the window. To allow a
136 menu to go outside of the window (to animate it moving into view, for
137 example), set the margins property to \c -1.
138
139 \section1 Dynamically Generating Menu Items
140
141 You can dynamically create menu items with \l Instantiator or
142 \l {Dynamic QML Object Creation from JavaScript} {dynamic object creation}.
143
144 \section2 Using Instantiator
145
146 You can dynamically generate menu items with \l Instantiator. The
147 following code shows how you can implement a "Recent Files" submenu,
148 where the items come from a list of files stored in settings:
149
150 \snippet qtquickcontrols-menu-instantiator.qml menu
151
152 \section2 Using Dynamic Object Creation
153
154 You can also dynamically load a component from a QML file using
155 \l {QtQml::Qt::createComponent()} {Qt.createComponent()}. Once the component
156 is ready, you can call its \l {Component::createObject()} {createObject()}
157 method to create an instance of that component.
158
159 \snippet qtquickcontrols-menu-createObject.qml createObject
160
161 \sa {Customizing Menu}, MenuItem, {Menu Controls}, {Popup Controls},
162 {Dynamic QML Object Creation from JavaScript}
163
164 \section1 Menu types
165
166 Since Qt 6.8, a menu offers three different implementations, depending on the
167 platform. You can choose which one should be preferred by setting
168 \l [QML] {Popup::} {popupType}. This will let you control if a menu should
169 be shown as a separate window, as an item inside the parent window, or as a
170 native menu. You can read more about these options \l{Popup type}{here}.
171
172 The default \l [QML] {Popup::}{popupType} is decided by the style. The \l {macOS Style}, for example,
173 sets it to be \c Popup.Native, while the \l{Imagine Style} uses \c Popup.Window (which
174 is the default when the style doesn't set a popup type).
175 If you add customizations to a menu, and want those to be used regardless of the
176 style, you should set the popup type to be \c Popup.Window (or \c Popup.Item) explicitly.
177 Another alternative is to set the \c Qt::AA_DontUseNativeMenuWindows
178 \l {Qt::ApplicationAttribute}{application attribute}. This will disable native context
179 menus for the whole application, irrespective of the style.
180
181 Whether a menu will be able to use the preferred type depends on the platform.
182 \c Popup.Item is supported on all platforms, but \c Popup.Window is
183 normally only supported on desktop platforms. Additionally, if the menu is inside
184 a \l {Native menu bars}{native menubar}, the menu will be native as well. And if
185 the menu is a sub-menu inside another menu, the parent (or root) menu will decide the type.
186
187 \section2 Limitations when using native menus
188
189 When setting \l [QML] {Popup::} {popupType} to \c Popup.Native
190 there are some limitations and differences compared to using \c Popup.Item
191 and \c Popup.Window.
192
193 \section3 API differences
194
195 When using native menus, only a subset of the Menu API is supported on all platforms:
196
197 \list
198 \li \l {Popup::}{x}
199 \li \l {Popup::}{y}
200 \li \l {Popup::}{visible}
201 \li \l {Popup::}{opened}
202 \li \l title
203 \li \l count
204 \li \l {Popup::}{contentData}
205 \li \l {Popup::}{contentChildren} (visual children will not be visible)
206 \li \l contentModel
207 \li \l {Popup::}{open()}
208 \li \l popup()
209 \li \l {Popup::}{close()}
210 \li \l {Popup::}{opened()}
211 \li \l {Popup::}{closed()}
212 \li \l {Popup::}{aboutToShow()}
213 \li \l {Popup::}{aboutToHide()}
214 \endlist
215
216 In addition, showing a popup (using, for example, \l {Popup::}{open()} or \l
217 {popup()}) will be a blocking call on some platforms. This means that the
218 call will not return before the menu is closed again, which can affect the
219 logic in your application. This is especially important to take into
220 consideration if your application is targeting multiple
221 platforms, and as such, sometimes run on platforms where native menus are
222 not supported. In that case the popupType will fall back to \c Popup.Item,
223 for example, and calls to \l {Popup::}{open()} will not be blocking.
224
225 Items like \l MenuItem will still react to clicks in the corresponding
226 native menu item by emitting signals, for example, but will be replaced by
227 their native counterpart.
228
229 \section3 Rendering differences
230
231 Native menus are implemented using the available native menu APIs on the platform.
232 Those menus, and all of their contents, will therefore be rendered by the platform, and
233 not by QML. This means that the \l delegate will \e not be used for rendering. It will,
234 however, always be instantiated (but hidden), so that functions such as
235 \l [QML] {QtQml::Component::completed}{onCompleted()} execute regardless of platform and
236 \l [QML] {Popup::} {popupType}.
237
238 \section3 Supported platforms
239
240 Native menus are currently supported on the following platforms:
241
242 \list
243 \li Android
244 \li iOS
245 \li Linux (only available as a stand-alone context menu when running with the GTK+ platform theme)
246 \li macOS
247 \li Windows
248 \endlist
249
250 \sa {Popup type}, [QML] {Popup::}{popupType}
251*/
252
253/*!
254 \qmlproperty bool QtQuick.Controls::Menu::focus
255
256 This property holds whether the popup wants focus.
257
258 When the popup actually receives focus, \l{Popup::}{activeFocus}
259 will be \c true. For more information, see
260 \l {Keyboard Focus in Qt Quick}.
261
262 The default value is \c true.
263
264 \include qquickmenu.qdocinc non-native-only-property
265
266 \sa {Popup::}{activeFocus}
267*/
268
269static const QQuickPopup::ClosePolicy cascadingSubMenuClosePolicy = QQuickPopup::CloseOnEscape | QQuickPopup::CloseOnPressOutsideParent | QQuickPopup::CloseMultiple;
270
271static bool shouldCascade()
272{
273#if QT_CONFIG(cursor)
274 return QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::MultipleWindows);
275#else
276 return false;
277#endif
278}
279
281{
282public:
284
286};
287
288QQuickMenuPrivate::QQuickMenuPrivate()
289{
290 cascade = shouldCascade();
291#if QT_CONFIG(wayland)
292 extendedWindowType = QNativeInterface::Private::QWaylandWindow::Menu;
293#endif
294#if QT_CONFIG(xcb)
295 wmWindowType = QNativeInterface::Private::QXcbWindow::PopupMenu;
296#endif
297}
298
299void QQuickMenuPrivate::init()
300{
301 Q_Q(QQuickMenu);
302 contentModel = new QQmlObjectModel(q);
303}
304
305QQuickMenu *QQuickMenuPrivate::rootMenu() const
306{
307 Q_Q(const QQuickMenu);
308 const QQuickMenu *rootMenu = q;
309 const QObject *p = q->parent();
310 while (p) {
311 if (auto menu = qobject_cast<const QQuickMenu *>(p))
312 rootMenu = menu;
313 p = p->parent();
314 }
315
316 return const_cast<QQuickMenu *>(rootMenu);
317}
318
319QQuickPopup::PopupType QQuickMenuPrivate::resolvedPopupType() const
320{
321 // The root menu (which can be this menu, unless it's a
322 // sub menu) decides the popup type for all sub menus.
323 QQuickMenu *root = rootMenu();
324 QQuickMenuPrivate *root_d = QQuickMenuPrivate::get(rootMenu());
325
326#if QT_CONFIG(quicktemplates2_container)
327 if (auto menuBar = QQuickMenuPrivate::get(root)->menuBar.get()) {
328 // When a menu is inside a MenuBar, the MenuBar decides if the menu
329 // should be native or not. The menu's popupType is therefore ignored.
330 // Basically, a native MenuBar can only contain native Menus, and
331 // a non-native MenuBar can only contain non-native Menus.
332 if (QQuickMenuBarPrivate::get(menuBar)->useNativeMenu(q_func()))
333 return QQuickPopup::Native;
334 } else
335#endif
336 {
337 // If the root menu is native, this menu needs to be native as well
338 if (root_d->maybeNativeHandle()) {
339 return QQuickPopup::Native;
340 } else if (!root_d->triedToCreateNativeMenu) {
341 // If popupType is Native, and native popups seems to be available, then we return
342 // the resolved type to be Native. But note that this doesn't guarantee that the
343 // menu will actually become native. QPA can still refuse to create a QPlaformMenu,
344 // if the QPA plugin or theme doesn't support it. The only way to know for sure if
345 // a menu became native, is to also check QQuickMenuPrivate::nativeHandle().
346 if (root->popupType() == QQuickPopup::Native
347 && !QGuiApplication::testAttribute(Qt::AA_DontUseNativeMenuWindows)) {
348 return QQuickPopup::Native;
349 }
350 }
351 }
352
353 // Let QQuickPopup decide if the menu should be Popup.Window or Popup.Item, based
354 // on e.g popuptype and platform limitations. QQuickPopupPrivate should never resolve
355 // the popup type to be Native, since that's up to the individual subclasses to decide.
356 const auto type = root_d->QQuickPopupPrivate::resolvedPopupType();
357 Q_ASSERT(type != QQuickPopup::Native);
358 return type;
359}
360
361bool QQuickMenuPrivate::useNativeMenu() const
362{
363 return resolvedPopupType() == QQuickPopup::Native;
364}
365
366QPlatformMenu *QQuickMenuPrivate::nativeHandle()
367{
368 Q_ASSERT(handle || useNativeMenu());
369 if (!handle && !triedToCreateNativeMenu)
370 createNativeMenu();
371 return handle.get();
372}
373
374QPlatformMenu *QQuickMenuPrivate::maybeNativeHandle() const
375{
376 return handle.get();
377}
378
379bool QQuickMenuPrivate::createNativeMenu()
380{
381 Q_ASSERT(!handle);
382 Q_Q(QQuickMenu);
383 qCDebug(lcNativeMenus) << "createNativeMenu called on" << q;
384
385 if (auto menuBar = QQuickMenuPrivate::get(rootMenu())->menuBar) {
386#if QT_CONFIG(quicktemplates2_container)
387 auto menuBarPrivate = QQuickMenuBarPrivate::get(menuBar);
388 if (menuBarPrivate->useNativeMenuBar()) {
389 qCDebug(lcNativeMenus) << "- creating native menu from native menubar";
390 if (QPlatformMenuBar *menuBarHandle = menuBarPrivate->nativeHandle())
391 handle.reset(menuBarHandle->createMenu());
392 }
393#endif
394 }
395
396 if (!handle) {
397 QPlatformMenu *parentMenuHandle(parentMenu ? get(parentMenu)->handle.get() : nullptr);
398 if (parentMenu && parentMenuHandle) {
399 qCDebug(lcNativeMenus) << "- creating native sub-menu";
400 handle.reset(parentMenuHandle->createSubMenu());
401 } else {
402 qCDebug(lcNativeMenus) << "- creating native menu";
403 handle.reset(QGuiApplicationPrivate::platformTheme()->createPlatformMenu());
404 }
405 }
406
407 triedToCreateNativeMenu = true;
408
409 if (!handle)
410 return false;
411
412 q->connect(handle.get(), &QPlatformMenu::aboutToShow, q, [q, this](){
413 emit q->aboutToShow();
414 visible = true;
415 emit q->visibleChanged();
416 emit q->openedChanged();
417 opened();
418 });
419 q->connect(handle.get(), &QPlatformMenu::aboutToHide, q, [q](){
420 qCDebug(lcNativeMenus) << "QPlatformMenu::aboutToHide called; about to call setVisible(false) on Menu";
421 emit q->aboutToHide();
422 });
423 // On some platforms (Windows and macOS), it can happen that QPlatformMenuItem::activated
424 // is emitted after QPlatformMenu::aboutToHide. Since sending signals out of order can
425 // cause an application to fail (QTBUG-128158) we use Qt::QueuedConnection to work around
426 // this, so that we emit the signals in the right order.
427 q->connect(handle.get(), &QPlatformMenu::aboutToHide, q, [q, this](){
428 visible = false;
429 emit q->visibleChanged();
430 emit q->openedChanged();
431 emit q->closed();
432 }, Qt::QueuedConnection);
433
434 recursivelyCreateNativeMenuItems(q);
435 syncWithNativeMenu();
436
437 return true;
438}
439
440QString nativeMenuItemListToString(const QList<QQuickNativeMenuItem *> &nativeItems)
441{
442 if (nativeItems.isEmpty())
443 return QStringLiteral("(Empty)");
444
445 QString str;
446 QTextStream debug(&str);
447 for (const auto *nativeItem : nativeItems)
448 debug << nativeItem->debugText() << ", ";
449 // Remove trailing space and comma.
450 if (!nativeItems.isEmpty())
451 str.chop(2);
452 return str;
453}
454
455void QQuickMenuPrivate::syncWithNativeMenu()
456{
457 Q_Q(QQuickMenu);
458 if (!complete || !handle)
459 return;
460
461 qCDebug(lcNativeMenus).nospace() << "syncWithNativeMenu called on " << q
462 << " (complete: " << complete << " visible: " << visible << ") - "
463 << "syncing " << nativeItems.size() << " item(s)...";
464
465 // TODO: call this function when any of the variables below change
466
467 handle->setText(title);
468 handle->setEnabled(q->isEnabled());
469 handle->setMinimumWidth(q->implicitWidth());
470// nativeHandle->setMenuType(m_type);
471 handle->setFont(q->font());
472
473 // Note: the QQuickMenu::visible property is used to open or close the menu.
474 // This is in contrast to QPlatformMenu::visible, which tells if the menu
475 // should be visible in the menubar or not (if it belongs to one). To control
476 // if a QPlatformMenu should be open, we instead use QPlatformMenu::showPopup()
477 // and dismiss(). As such, we don't want to call handle->setVisible(visible)
478 // from this function since we always want the menu to be visible in the menubar
479 // (if it belongs to one). The currently only way to hide a menu from a menubar is
480 // to instead call MenuBar.removeMenu(menu).
481
482// if (m_menuBar && m_menuBar->handle())
483// m_menuBar->handle()->syncMenu(handle);
484//#if QT_CONFIG(systemtrayicon)
485// else if (m_systemTrayIcon && m_systemTrayIcon->handle())
486// m_systemTrayIcon->handle()->updateMenu(handle);
487//#endif
488
489 for (QQuickNativeMenuItem *item : std::as_const(nativeItems)) {
490 qCDebug(lcNativeMenus) << "- syncing" << item << "action" << item->action()
491 << "sub-menu" << item->subMenu() << item->debugText();
492 item->sync();
493 }
494
495 qCDebug(lcNativeMenus) << "... finished syncing" << q;
496}
497
498/*!
499 \internal
500
501 Removes the native menu, including its native menu items.
502
503 \note this doesn't remove any QQuickMenuItems from the contentModel;
504 it merely removes the associated native menu items.
505*/
506void QQuickMenuPrivate::removeNativeMenu()
507{
508 Q_Q(QQuickMenu);
509 const int qtyItemsToRemove = nativeItems.size();
510 if (qtyItemsToRemove != 0)
511 Q_ASSERT(q->count() == qtyItemsToRemove);
512 for (int i = 0; i < qtyItemsToRemove; ++i)
513 removeNativeItem(0);
514 Q_ASSERT(nativeItems.isEmpty());
515
516 // removeNativeItem will take care of destroying sub-menus and resetting their native data,
517 // but as the root menu, we have to take care of our own.
518 resetNativeData();
519}
520
521void QQuickMenuPrivate::syncWithUseNativeMenu()
522{
523 Q_Q(QQuickMenu);
524 // Users can change AA_DontUseNativeMenuWindows while a menu is visible,
525 // but the changes won't take affect until the menu is re-opened.
526 if (q->isVisible() || parentMenu)
527 return;
528
529 if (maybeNativeHandle() && !useNativeMenu()) {
530 // Switch to a non-native menu by removing the native menu and its native items.
531 // Note that there's nothing to do if a native menu was requested but we failed to create it.
532 removeNativeMenu();
533 } else if (useNativeMenu()) {
534 Q_ASSERT(nativeItems.isEmpty());
535 // Try to create a native menu.
536 nativeHandle();
537 }
538}
539
540void QQuickMenuPrivate::setNativeMenuVisible(bool visible)
541{
542 qCDebug(lcNativeMenus) << "setNativeMenuVisible called with visible" << visible;
543
544 this->visible = visible;
545 syncWithNativeMenu();
546
547 if (visible) {
548 QPoint offset;
549 QWindow *window = nullptr;
550 if (parentItem)
551 window = QQuickItemPrivate::get(parentItem)->renderWindow(&offset);
552
553 lastDevicePixelRatio = window ? window->devicePixelRatio() : qGuiApp->devicePixelRatio();
554
555 const QPointF globalPos = parentItem->mapToGlobal(x, y);
556 const QPoint windowPos = window ? window->mapFromGlobal(globalPos.toPoint()) : parentItem->mapToScene(QPoint(x, y)).toPoint();
557 QRect targetRect(windowPos, QSize(0, 0));
558 auto *daPriv = QQuickItemPrivate::get(parentItem)->deliveryAgentPrivate();
559 Q_ASSERT(daPriv);
560 // A menu is typically opened when some event-handling object (like TapHandler) calls
561 // QQuickMenu::popup(). We don't have the event or the caller available directly here.
562 // But showPopup() below is expected to "eat" the release event, so
563 // the caller will not see it. Cancel all grabs so that the object that
564 // handled the press event will not get stuck in pressed state.
565 if (QPointerEvent *openingEvent = daPriv->eventInDelivery()) {
566 auto *devPriv = QPointingDevicePrivate::get(const_cast<QPointingDevice *>(openingEvent->pointingDevice()));
567 for (const auto &pt : std::as_const(openingEvent->points())) {
568 qCDebug(lcNativeMenus) << "popup over" << window << "its DA" << daPriv->q_func() << "opening due to" << openingEvent
569 << "with grabbers" << openingEvent->exclusiveGrabber(pt) << openingEvent->passiveGrabbers(pt);
570
571 if (auto *opener = openingEvent->exclusiveGrabber(pt))
572 devPriv->removeGrabber(opener, true); // cancel
573 for (auto passiveGrabber : openingEvent->passiveGrabbers(pt)) {
574 if (auto *opener = passiveGrabber.get())
575 devPriv->removeGrabber(opener, true); // cancel
576 }
577 }
578 }
579 handle->showPopup(window, QHighDpi::toNativeLocalPosition(targetRect, window),
580 /*menuItem ? menuItem->handle() : */nullptr);
581 } else {
582 handle->dismiss();
583 }
584}
585
586// Used by QQuickContextMenu when it's opened on a text-editing control.
587void QQuickMenuPrivate::makeEditMenu()
588{
589 if (!handle)
590 syncWithUseNativeMenu();
591 if (handle)
592 handle->setMenuType(QPlatformMenu::EditMenu);
593}
594
595QQuickItem *QQuickMenuPrivate::itemAt(int index) const
596{
597 return qobject_cast<QQuickItem *>(contentModel->get(index));
598}
599
600void QQuickMenuPrivate::insertItem(int index, QQuickItem *item)
601{
602 qCDebug(lcMenu) << "insert called with index" << index << "item" << item;
603
604 Q_Q(QQuickMenu);
605 contentData.append(item);
606 item->setParentItem(contentItem);
607 QQuickItemPrivate::get(item)->setCulled(true); // QTBUG-53262
608 if (complete)
609 resizeItem(item);
610 QQuickItemPrivate::get(item)->addItemChangeListener(this, QQuickItemPrivate::Destroyed | QQuickItemPrivate::Parent | QQuickItemPrivate::ImplicitWidth);
611 QQuickItemPrivate::get(item)->updateOrAddGeometryChangeListener(this, QQuickGeometryChange::Width);
612 contentModel->insert(index, item);
613
614 QQuickMenuItem *menuItem = qobject_cast<QQuickMenuItem *>(item);
615 if (menuItem) {
616 QQuickMenuItemPrivate::get(menuItem)->setMenu(q);
617 if (QQuickMenu *subMenu = menuItem->subMenu())
618 QQuickMenuPrivate::get(subMenu)->setParentMenu(q);
619 QObjectPrivate::connect(menuItem, &QQuickMenuItem::triggered, this, &QQuickMenuPrivate::onItemTriggered);
620 QObjectPrivate::connect(menuItem, &QQuickMenuItem::implicitTextPaddingChanged, this, &QQuickMenuPrivate::updateTextPadding);
621 QObjectPrivate::connect(menuItem, &QQuickMenuItem::visibleChanged, this, &QQuickMenuPrivate::onItemVisibleChanged);
622 QObjectPrivate::connect(menuItem, &QQuickItem::activeFocusChanged, this, &QQuickMenuPrivate::onItemActiveFocusChanged);
623 QObjectPrivate::connect(menuItem, &QQuickControl::hoveredChanged, this, &QQuickMenuPrivate::onItemHovered);
624 }
625
626 QQuickMenuSeparator *separator = qobject_cast<QQuickMenuSeparator *>(item);
627 if (separator)
628 QObjectPrivate::connect(separator, &QQuickMenuSeparator::visibleChanged, this, &QQuickMenuPrivate::updateCollapsedSeparators);
629
630 if (maybeNativeHandle() && complete)
631 maybeCreateAndInsertNativeItem(index, item);
632
633 if (lcMenu().isDebugEnabled())
634 printContentModelItems();
635
636 updateTextPadding();
637 updateContentWidth();
638 if (visible)
639 updateCollapsedSeparators();
640}
641
642void QQuickMenuPrivate::maybeCreateAndInsertNativeItem(int index, QQuickItem *item)
643{
644 Q_Q(QQuickMenu);
645 Q_ASSERT(complete);
646 Q_ASSERT_X(handle, Q_FUNC_INFO, qPrintable(QString::fromLatin1(
647 "Expected %1 to be using a native menu").arg(QDebug::toString(q))));
648 std::unique_ptr<QQuickNativeMenuItem> nativeMenuItem(QQuickNativeMenuItem::createFromNonNativeItem(q, item));
649 if (!nativeMenuItem) {
650 // TODO: fall back to non-native menu
651 qmlWarning(q) << "Native menu failed to create a native menu item for item at index" << index;
652 return;
653 }
654
655 nativeItems.insert(index, nativeMenuItem.get());
656
657 // Having a QQuickNativeMenuItem doesn't mean that we were able to create a native handle:
658 // it could be e.g. a Rectangle. See comment in QQuickNativeMenuItem::createFromNonNativeItem.
659 if (nativeMenuItem->handle()) {
660 QQuickNativeMenuItem *before = nativeItems.value(index + 1);
661 handle->insertMenuItem(nativeMenuItem->handle(), before ? before->handle() : nullptr);
662 qCDebug(lcNativeMenus) << "inserted native menu item at index" << index
663 << "before" << (before ? before->debugText() : QStringLiteral("null"));
664
665 if (nativeMenuItem->subMenu() && QQuickMenuPrivate::get(nativeMenuItem->subMenu())->nativeItems.count()
666 < nativeMenuItem->subMenu()->count()) {
667 // We're inserting a sub-menu item, and it hasn't had native items added yet,
668 // which probably means it's a menu that's been added back in after being removed
669 // with takeMenu(). Sub-menus added for the first time have their native items already
670 // constructed by virtue of contentData_append. Sub-menus that are removed always
671 // have their native items destroyed and removed too.
672 recursivelyCreateNativeMenuItems(nativeMenuItem->subMenu());
673 }
674 }
675
676 nativeMenuItem.release();
677
678 qCDebug(lcNativeMenus) << "nativeItems now contains the following items:"
679 << nativeMenuItemListToString(nativeItems);
680}
681
682void QQuickMenuPrivate::moveItem(int from, int to)
683{
684 contentModel->move(from, to);
685
686 if (maybeNativeHandle())
687 nativeItems.move(from, to);
688}
689
690/*!
691 \internal
692
693 Removes the specified \a item, potentially destroying it depending on
694 \a destructionPolicy.
695
696 \note the native menu item is destroyed regardless of the destruction
697 policy, because it's an implementation detail and hence is not created by
698 or available to the user.
699*/
700void QQuickMenuPrivate::removeItem(int index, QQuickItem *item, DestructionPolicy destructionPolicy)
701{
702 qCDebug(lcMenu) << "removeItem called with index" << index << "item" << item;
703
704 if (maybeNativeHandle())
705 removeNativeItem(index);
706
707 contentData.removeOne(item);
708
709 QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Destroyed | QQuickItemPrivate::Parent | QQuickItemPrivate::ImplicitWidth);
710 QQuickItemPrivate::get(item)->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
711 item->setParentItem(nullptr);
712 contentModel->remove(index);
713
714 QQuickMenuItem *menuItem = qobject_cast<QQuickMenuItem *>(item);
715 if (menuItem) {
716 QQuickMenuItemPrivate::get(menuItem)->setMenu(nullptr);
717 if (QQuickMenu *subMenu = menuItem->subMenu())
718 QQuickMenuPrivate::get(subMenu)->setParentMenu(nullptr);
719 QObjectPrivate::disconnect(menuItem, &QQuickMenuItem::triggered, this, &QQuickMenuPrivate::onItemTriggered);
720 QObjectPrivate::disconnect(menuItem, &QQuickMenuItem::implicitTextPaddingChanged, this, &QQuickMenuPrivate::updateTextPadding);
721 QObjectPrivate::disconnect(menuItem, &QQuickMenuItem::visibleChanged, this, &QQuickMenuPrivate::onItemVisibleChanged);
722 QObjectPrivate::disconnect(menuItem, &QQuickItem::activeFocusChanged, this, &QQuickMenuPrivate::onItemActiveFocusChanged);
723 QObjectPrivate::disconnect(menuItem, &QQuickControl::hoveredChanged, this, &QQuickMenuPrivate::onItemHovered);
724 }
725
726 QQuickMenuSeparator *separator = qobject_cast<QQuickMenuSeparator *>(item);
727 if (separator) {
728 QObjectPrivate::disconnect(separator, &QQuickMenuSeparator::visibleChanged, this, &QQuickMenuPrivate::updateCollapsedSeparators);
729 collapsedSeparators.remove(item);
730 }
731
732 if (destructionPolicy == DestructionPolicy::Destroy)
733 item->deleteLater();
734
735 if (lcMenu().isDebugEnabled())
736 printContentModelItems();
737
738 updateContentWidth();
739 if (visible)
740 updateCollapsedSeparators();
741}
742
743/*!
744 \internal
745
746 Removes the native menu item at \a index from this menu.
747
748 \note this doesn't remove the QQuickMenuItem from the contentModel;
749 it merely removes the associated native menu item. It's for this reason
750 that this is a separate function to removeItem, which \e does remove
751 the QQuickMenuItem.
752*/
753void QQuickMenuPrivate::removeNativeItem(int index, SyncPolicy syncPolicy)
754{
755 // Either we're still using native menus and are removing item(s), or we've switched
756 // to a non-native menu; either way, we should actually have items to remove before we're called.
757 Q_ASSERT(handle);
758 Q_ASSERT_X(index >= 0 && index < nativeItems.size(), Q_FUNC_INFO, qPrintable(QString::fromLatin1(
759 "index %1 is less than 0 or greater than or equal to %2").arg(index).arg(nativeItems.size())));
760
761 // We can delete the item synchronously because there aren't any external (e.g. QML)
762 // references to it.
763 std::unique_ptr<QQuickNativeMenuItem> nativeItem(nativeItems.takeAt(index));
764 qCDebug(lcNativeMenus) << "removing native item" << nativeItem->debugText() << "at index" << index
765 << "from" << q_func() << "...";
766 QQuickMenu *subMenu = nativeItem->subMenu();
767 if (subMenu) {
768 Q_ASSERT(nativeItem->handle());
769 auto *subMenuPrivate = QQuickMenuPrivate::get(subMenu);
770 while (!subMenuPrivate->nativeItems.isEmpty()) {
771 subMenuPrivate->removeNativeItem(0, SyncPolicy::DoNotSync);
772 }
773 }
774
775 Q_ASSERT(nativeItem->handle());
776 handle->removeMenuItem(nativeItem->handle());
777 if (syncPolicy == SyncPolicy::Sync)
778 syncWithNativeMenu();
779
780 if (subMenu) {
781 auto *subMenuPrivate = QQuickMenuPrivate::get(subMenu);
782 // Reset the item's data. This is important as it avoids accessing a deleted
783 // QQuickAction when printing in QQuickNativeMenuItem's destructor.
784 // It's also important that we do this _after_ the removeMenuItem call above,
785 // because otherwise we sever the connection between the sub and parent menu,
786 // which causes warnings in QCocoaMenu::removeMenuItem.
787 subMenuPrivate->resetNativeData();
788 }
789
790 qCDebug(lcNativeMenus).nospace() << "... after removing item at index " << index
791 << ", nativeItems now contains the following items: " << nativeMenuItemListToString(nativeItems);
792}
793
794void QQuickMenuPrivate::resetNativeData()
795{
796 qCDebug(lcNativeMenus) << "resetNativeData called on" << q_func();
797 handle.reset();
798 triedToCreateNativeMenu = false;
799}
800
801void QQuickMenuPrivate::recursivelyCreateNativeMenuItems(QQuickMenu *menu)
802{
803 auto *menuPrivate = QQuickMenuPrivate::get(menu);
804 // If we're adding a sub-menu, we need to ensure its handle has been created
805 // before trying to create native items for it.
806 if (!menuPrivate->triedToCreateNativeMenu)
807 menuPrivate->createNativeMenu();
808
809 const int qtyItemsToCreate = menuPrivate->contentModel->count();
810 if (menuPrivate->nativeItems.count() == qtyItemsToCreate)
811 return;
812
813 qCDebug(lcNativeMenus) << "recursively creating" << qtyItemsToCreate << "menu item(s) for" << menu;
814 Q_ASSERT(menuPrivate->nativeItems.count() == 0);
815 for (int i = 0; i < qtyItemsToCreate; ++i) {
816 QQuickItem *item = menu->itemAt(i);
817 menuPrivate->maybeCreateAndInsertNativeItem(i, item);
818 auto *menuItem = qobject_cast<QQuickMenuItem *>(item);
819 if (menuItem && menuItem->subMenu())
820 recursivelyCreateNativeMenuItems(menuItem->subMenu());
821 }
822}
823
824void QQuickMenuPrivate::printContentModelItems() const
825{
826 qCDebug(lcMenu) << "contentModel now contains:";
827 for (int i = 0; i < contentModel->count(); ++i)
828 qCDebug(lcMenu) << "-" << itemAt(i);
829}
830
831QQuickItem *QQuickMenuPrivate::beginCreateItem()
832{
833 Q_Q(QQuickMenu);
834 if (!delegate)
835 return nullptr;
836
837 QQmlContext *context = delegate->creationContext();
838 if (!context)
839 context = qmlContext(q);
840
841 QObject *object = delegate->beginCreate(context);
842 QQuickItem *item = qobject_cast<QQuickItem *>(object);
843 if (!item)
844 delete object;
845 else
846 QQml_setParent_noEvent(item, q);
847
848 return item;
849}
850
851void QQuickMenuPrivate::completeCreateItem()
852{
853 if (!delegate)
854 return;
855
856 delegate->completeCreate();
857}
858
859QQuickItem *QQuickMenuPrivate::createItem(QQuickMenu *menu)
860{
861 QQuickItem *item = beginCreateItem();
862 if (QQuickMenuItem *menuItem = qobject_cast<QQuickMenuItem *>(item))
863 QQuickMenuItemPrivate::get(menuItem)->setSubMenu(menu);
864 completeCreateItem();
865 return item;
866}
867
868QQuickItem *QQuickMenuPrivate::createItem(QQuickAction *action)
869{
870 QQuickItem *item = beginCreateItem();
871 if (QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(item))
872 button->setAction(action);
873 completeCreateItem();
874 return item;
875}
876
877void QQuickMenuPrivate::resizeItem(QQuickItem *item)
878{
879 if (!item || !contentItem)
880 return;
881
882 QQuickItemPrivate *p = QQuickItemPrivate::get(item);
883 if (!p->widthValid()) {
884 item->setWidth(contentItem->width());
885 p->widthValidFlag = false;
886 }
887}
888
889void QQuickMenuPrivate::resizeItems()
890{
891 if (!contentModel)
892 return;
893
894 for (int i = 0; i < contentModel->count(); ++i)
895 resizeItem(itemAt(i));
896}
897
898void QQuickMenuPrivate::itemChildAdded(QQuickItem *, QQuickItem *child)
899{
900 // add dynamically reparented items (eg. by a Repeater)
901 if (!QQuickItemPrivate::get(child)->isTransparentForPositioner() && !contentData.contains(child))
902 insertItem(contentModel->count(), child);
903}
904
905void QQuickMenuPrivate::itemParentChanged(QQuickItem *item, QQuickItem *parent)
906{
907 // remove dynamically unparented items (eg. by a Repeater)
908 if (!parent)
909 removeItem(contentModel->indexOf(item, nullptr), item);
910}
911
912void QQuickMenuPrivate::itemSiblingOrderChanged(QQuickItem *)
913{
914 // reorder the restacked items (eg. by a Repeater)
915 Q_Q(QQuickMenu);
916 QList<QQuickItem *> siblings = contentItem->childItems();
917
918 int to = 0;
919 for (int i = 0; i < siblings.size(); ++i) {
920 QQuickItem* sibling = siblings.at(i);
921 if (QQuickItemPrivate::get(sibling)->isTransparentForPositioner())
922 continue;
923 int index = contentModel->indexOf(sibling, nullptr);
924 q->moveItem(index, to++);
925 }
926}
927
928void QQuickMenuPrivate::itemDestroyed(QQuickItem *item)
929{
930 if (item == contentItem) {
931 resetContentItem();
932 } else {
933 QQuickPopupPrivate::itemDestroyed(item);
934 if (contentModel) {
935 int index = contentModel->indexOf(item, nullptr);
936 if (index != -1)
937 removeItem(index, item);
938 }
939 }
940}
941
942void QQuickMenuPrivate::itemGeometryChanged(QQuickItem *item, QQuickGeometryChange, const QRectF &)
943{
944 if (!complete)
945 return;
946
947 if (item == contentItem) {
948 // The contentItem's geometry changed, so resize any items
949 // that don't have explicit widths set so that they fill the width of the menu.
950 resizeItems();
951 } else {
952 // The geometry of an item in the menu changed. If the item
953 // doesn't have an explicit width set, make it fill the width of the menu.
954 resizeItem(item);
955 }
956}
957
958void QQuickMenuPrivate::itemImplicitWidthChanged(QQuickItem *item)
959{
960 if (item != contentItem)
961 updateContentWidth();
962}
963
964void QQuickMenuPrivate::updateContentWidth()
965{
966 if (!contentModel || !contentItem)
967 return;
968
969 Q_Q(QQuickMenu);
970 qreal maxWidth = 0;
971 for (int i = 0; i < contentModel->count(); ++i) {
972 QQuickItem *item = q->itemAt(i);
973 if (item && QQuickItemPrivate::get(item)->explicitVisible)
974 maxWidth = qMax(maxWidth, item->implicitWidth());
975 }
976
977 // Set the implicitWidth on the contentItem (ListView) so that the
978 // menu expands to fit its widest item. An explicit contentWidth on
979 // the Menu takes precedence over this value.
980 if (!qFuzzyIsNull(maxWidth))
981 contentItem->setImplicitWidth(maxWidth);
982}
983
984QQuickPopupPositioner *QQuickMenuPrivate::getPositioner()
985{
986 Q_Q(QQuickMenu);
987 if (!positioner)
988 positioner = new QQuickMenuPositioner(q);
989 return positioner;
990}
991
993{
994 QQuickMenu *menu = static_cast<QQuickMenu *>(popup());
995 QQuickMenuPrivate *menu_d = QQuickMenuPrivate::get(menu);
996
997 if (QQuickMenu *parentMenu = menu_d->parentMenu) {
998 if (menu_d->cascade) {
999 // Align the menu to the frame of the parent menuItem, minus overlap. The position
1000 // should be in the coordinate system of the parentItem.
1001 if (menu_d->popupItem->isMirrored()) {
1002 const qreal distanceToFrame = parentMenu->leftPadding();
1003 const qreal menuX = -menu->width() - distanceToFrame + menu->overlap();
1004 menu->setPosition({menuX, -menu->topPadding()});
1005 } else if (menu_d->parentItem) {
1006 const qreal distanceToFrame = parentMenu->rightPadding();
1007 const qreal menuX = menu_d->parentItem->width() + distanceToFrame - menu->overlap();
1008 menu->setPosition({menuX, -menu->topPadding()});
1009 }
1010 } else {
1011 const qreal menuX = parentMenu->x() + (parentMenu->width() - menu->width()) / 2;
1012 const qreal menuY = parentMenu->y() + (parentMenu->height() - menu->height()) / 2;
1013 menu->setPosition({menuX, menuY});
1014 }
1015 }
1016
1017 QQuickPopupPositioner::reposition();
1018}
1019
1020bool QQuickMenuPrivate::prepareEnterTransition()
1021{
1022 Q_Q(QQuickMenu);
1023 if (parentMenu && !cascade)
1024 parentMenu->close();
1025
1026 // If a cascading sub-menu doesn't have enough space to open on
1027 // the right, it flips on the other side of the parent menu.
1028 allowHorizontalFlip = cascade && parentMenu;
1029
1030 updateCollapsedSeparators();
1031
1032 // Enter transitions may want to animate the Menu's height based on its implicitHeight.
1033 // The Menu's implicitHeight is typically based on the ListView's contentHeight,
1034 // among other things. The docs for ListView's forceLayout function say:
1035 // "Responding to changes in the model is usually batched to happen only once per frame."
1036 // As e.g. NumberAnimation's from and to values are set before any polishes happen,
1037 // any re-evaluation of their bindings happen too late, and the starting height can be
1038 // out-dated when menu items are added after component completion
1039 // (QQuickItemView::componentComplete does a layout, so items declared as children aren't
1040 // affected by this). To account for this, we force a layout before the transition starts.
1041 // We try to avoid unnecessary re-layouting if we can avoid it.
1042 auto *contentItemAsListView = qobject_cast<QQuickListView *>(contentItem);
1043 if (contentItemAsListView) {
1044 if (QQuickItemViewPrivate::get(contentItemAsListView)->currentChanges.hasPendingChanges())
1045 contentItemAsListView->forceLayout();
1046 }
1047
1048 if (!QQuickPopupPrivate::prepareEnterTransition())
1049 return false;
1050
1051 if (!hasClosePolicy) {
1052 if (cascade && parentMenu)
1053 closePolicy = cascadingSubMenuClosePolicy;
1054 else
1055 q->resetClosePolicy();
1056 }
1057 return true;
1058}
1059
1060bool QQuickMenuPrivate::prepareExitTransition()
1061{
1062 if (!QQuickPopupPrivate::prepareExitTransition())
1063 return false;
1064
1065 stopHoverTimer();
1066
1067 QQuickMenu *subMenu = currentSubMenu();
1068 while (subMenu) {
1069 QPointer<QQuickMenuItem> currentSubMenuItem = QQuickMenuPrivate::get(subMenu)->currentItem;
1070 subMenu->close();
1071 subMenu = currentSubMenuItem ? currentSubMenuItem->subMenu() : nullptr;
1072 }
1073 return true;
1074}
1075
1076bool QQuickMenuPrivate::blockInput(QQuickItem *item, const QPointF &point) const
1077{
1078 // keep the parent menu open when a cascading sub-menu (this menu) is interacted with
1079 return (cascade && parentMenu && contains(point)) || QQuickPopupPrivate::blockInput(item, point);
1080}
1081
1082bool QQuickMenuPrivate::handlePress(QQuickItem *item, const QPointF &point, ulong timestamp)
1083{
1084 // Don't propagate mouse event as it can cause underlying item to receive
1085 // events
1086 return QQuickPopupPrivate::handlePress(item, point, timestamp)
1087 || (popupItem == item);
1088}
1089
1090
1091/*! \internal
1092 QQuickPopupWindow::event() calls this to handle the release event of a
1093 menu drag-press-release gesture, because the \a eventPoint does not have
1094 a grabber within the popup window. This override finds and activates the
1095 appropriate menu item, as if it had been pressed and released.
1096 Returns true on success, to indicate that handling \a eventPoint is done.
1097 */
1098bool QQuickMenuPrivate::handleReleaseWithoutGrab(const QEventPoint &eventPoint)
1099{
1100 const QPointF scenePos = eventPoint.scenePosition();
1101 if (!contains(scenePos))
1102 return false;
1103
1104 auto *list = qobject_cast<QQuickListView *>(contentItem);
1105 if (!list)
1106 return false;
1107
1108 const QPointF listPos = list->mapFromScene(scenePos);
1109
1110 auto *menuItem = qobject_cast<QQuickMenuItem *>(list->itemAt(listPos.x(), listPos.y()));
1111 if (menuItem && menuItem->isHighlighted()) {
1112 menuItem->animateClick();
1113 return true;
1114 }
1115
1116 return false;
1117}
1118
1119void QQuickMenuPrivate::onItemHovered()
1120{
1121 Q_Q(QQuickMenu);
1122 QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(q->sender());
1123 if (!button || !button->isHovered() || !button->isEnabled() || QQuickAbstractButtonPrivate::get(button)->touchId != -1)
1124 return;
1125
1126 QQuickMenuItem *oldCurrentItem = currentItem;
1127
1128 int index = contentModel->indexOf(button, nullptr);
1129 if (index != -1) {
1130 setCurrentIndex(index, Qt::OtherFocusReason);
1131 if (oldCurrentItem != currentItem) {
1132 if (oldCurrentItem) {
1133 QQuickMenu *subMenu = oldCurrentItem->subMenu();
1134 if (subMenu)
1135 subMenu->close();
1136 }
1137 if (currentItem) {
1138 QQuickMenu *subMenu = currentItem->menu();
1139 if (subMenu && subMenu->cascade())
1140 startHoverTimer();
1141 }
1142 }
1143 }
1144}
1145
1146void QQuickMenuPrivate::onItemTriggered()
1147{
1148 Q_Q(QQuickMenu);
1149 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(q->sender());
1150 if (!item)
1151 return;
1152
1153 if (QQuickMenu *subMenu = item->subMenu()) {
1154 auto subMenuPrivate = QQuickMenuPrivate::get(subMenu);
1155 subMenuPrivate->popup(subMenuPrivate->firstEnabledMenuItem());
1156 } else {
1157 q->dismiss();
1158 }
1159}
1160
1161void QQuickMenuPrivate::onItemActiveFocusChanged()
1162{
1163 Q_Q(QQuickMenu);
1164 QQuickItem *item = qobject_cast<QQuickItem*>(q->sender());
1165 if (!item->hasActiveFocus())
1166 return;
1167
1168 int indexOfItem = contentModel->indexOf(item, nullptr);
1169 QQuickControl *control = qobject_cast<QQuickControl *>(item);
1170 setCurrentIndex(indexOfItem, control ? control->focusReason() : Qt::OtherFocusReason);
1171}
1172
1173void QQuickMenuPrivate::onItemVisibleChanged()
1174{
1175 updateTextPadding();
1176 updateCollapsedSeparators();
1177}
1178
1179void QQuickMenuPrivate::updateTextPadding()
1180{
1181 Q_Q(QQuickMenu);
1182 if (!complete)
1183 return;
1184
1185 qreal padding = 0;
1186 for (int i = 0; i < q->count(); ++i) {
1187 if (const auto menuItem = qobject_cast<QQuickMenuItem *>(itemAt(i)))
1188 if (menuItem->isVisible())
1189 padding = qMax(padding, menuItem->implicitTextPadding());
1190 }
1191
1192 if (padding == textPadding)
1193 return;
1194
1195 textPadding = padding;
1196
1197 for (int i = 0; i < q->count(); ++i) {
1198 if (const auto menuItem = qobject_cast<QQuickMenuItem *>(itemAt(i)))
1199 emit menuItem->textPaddingChanged();
1200 }
1201}
1202
1203void QQuickMenuPrivate::updateCollapsedSeparators()
1204{
1205 if (!complete || updatingCollapsedSeparators)
1206 return;
1207
1208 // Guard against re-entrancy: setting visible on a separator will emit
1209 // visibleChanged, which is connected back to this function.
1210 QScopedValueRollback guard(updatingCollapsedSeparators, true);
1211
1212 auto isExplicitlyVisible = [](const QQuickItem *item) {
1213 return QQuickItemPrivate::get(item)->explicitVisible;
1214 };
1215
1216 auto hasVisibleBinding = [](QQuickItem *item) {
1217 static const int visibleIndex = QQuickItem::staticMetaObject.indexOfProperty("visible");
1218 auto ddata = QQmlData::get(item, false);
1219 if (!ddata)
1220 return false;
1221 return ddata->hasBindingBit(visibleIndex);
1222 };
1223
1224 auto hideSeparator = [this](QQuickItem *separatorItem) {
1225 separatorItem->setVisible(false);
1226 separatorItem->setHeight(0);
1227 collapsedSeparators.insert(separatorItem);
1228 };
1229
1230 auto showSeparator = [this](QQuickItem *separatorItem) {
1231 if (!collapsedSeparators.contains(separatorItem))
1232 return; // Only restore separators that we have previously collapsed
1233 separatorItem->setVisible(true);
1234 separatorItem->resetHeight();
1235 collapsedSeparators.remove(separatorItem);
1236 };
1237
1238 const int count = contentModel->count();
1239
1240 if (!collapsibleSeparators) {
1241 for (int i = 0; i < count; ++i)
1242 showSeparator(itemAt(i));
1243 return;
1244 }
1245
1246 QQuickItem *visibleSeparatorBefore = nullptr;
1247 bool hasVisibleItemBefore = false;
1248
1249 for (int i = 0; i < count; ++i) {
1250 QQuickItem *item = itemAt(i);
1251 if (!item)
1252 continue;
1253
1254 if (qobject_cast<QQuickMenuSeparator *>(item)) {
1255 if (hasVisibleBinding(item)) {
1256 if (isExplicitlyVisible(item) && !visibleSeparatorBefore)
1257 visibleSeparatorBefore = item;
1258 continue;
1259 }
1260
1261 if (visibleSeparatorBefore) {
1262 hideSeparator(item);
1263 } else if (hasVisibleItemBefore) {
1264 visibleSeparatorBefore = item;
1265 showSeparator(item);
1266 } else {
1267 hideSeparator(item);
1268 }
1269 } else if (isExplicitlyVisible(item)) {
1270 hasVisibleItemBefore = true;
1271 visibleSeparatorBefore = nullptr;
1272 }
1273 }
1274
1275 // Trailing separator
1276 if (visibleSeparatorBefore && !hasVisibleBinding(visibleSeparatorBefore))
1277 hideSeparator(visibleSeparatorBefore);
1278}
1279
1280QQuickMenu *QQuickMenuPrivate::currentSubMenu() const
1281{
1282 if (!currentItem)
1283 return nullptr;
1284
1285 return currentItem->subMenu();
1286}
1287
1288void QQuickMenuPrivate::setParentMenu(QQuickMenu *parent)
1289{
1290 Q_Q(QQuickMenu);
1291 if (parentMenu == parent)
1292 return;
1293
1294 if (parentMenu) {
1295 QObject::disconnect(parentMenu.data(), &QQuickMenu::cascadeChanged, q, &QQuickMenu::setCascade);
1296 disconnect(parentMenu.data(), &QQuickMenu::parentChanged, this, &QQuickMenuPrivate::resolveParentItem);
1297 }
1298 if (parent) {
1299 QObject::connect(parent, &QQuickMenu::cascadeChanged, q, &QQuickMenu::setCascade);
1300 connect(parent, &QQuickMenu::parentChanged, this, &QQuickMenuPrivate::resolveParentItem);
1301 }
1302
1303 parentMenu = parent;
1304 q->resetCascade();
1305 resolveParentItem();
1306}
1307
1308static QQuickItem *findParentMenuItem(QQuickMenu *subMenu)
1309{
1310 QQuickMenu *menu = QQuickMenuPrivate::get(subMenu)->parentMenu;
1311 for (int i = 0; i < QQuickMenuPrivate::get(menu)->contentModel->count(); ++i) {
1312 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(menu->itemAt(i));
1313 if (item && item->subMenu() == subMenu)
1314 return item;
1315 }
1316 return nullptr;
1317}
1318
1319void QQuickMenuPrivate::resolveParentItem()
1320{
1321 Q_Q(QQuickMenu);
1322 if (!parentMenu)
1323 q->resetParentItem();
1324 else if (!cascade)
1325 q->setParentItem(parentMenu->parentItem());
1326 else
1327 q->setParentItem(findParentMenuItem(q));
1328}
1329
1330void QQuickMenuPrivate::propagateKeyEvent(QKeyEvent *event)
1331{
1332 if (QQuickMenuItem *menuItem = qobject_cast<QQuickMenuItem *>(parentItem)) {
1333 if (QQuickMenu *menu = menuItem->menu())
1334 QQuickMenuPrivate::get(menu)->propagateKeyEvent(event);
1335#if QT_CONFIG(quicktemplates2_container)
1336 } else if (QQuickMenuBarItem *menuBarItem = qobject_cast<QQuickMenuBarItem *>(parentItem)) {
1337 if (QQuickMenuBar *menuBar = menuBarItem->menuBar()) {
1338 event->accept();
1339 QCoreApplication::sendEvent(menuBar, event);
1340 }
1341#endif
1342 }
1343}
1344
1345void QQuickMenuPrivate::startHoverTimer()
1346{
1347 Q_Q(QQuickMenu);
1348 stopHoverTimer();
1349 hoverTimer = q->startTimer(SUBMENU_DELAY);
1350}
1351
1352void QQuickMenuPrivate::stopHoverTimer()
1353{
1354 Q_Q(QQuickMenu);
1355 if (!hoverTimer)
1356 return;
1357
1358 q->killTimer(hoverTimer);
1359 hoverTimer = 0;
1360}
1361
1362void QQuickMenuPrivate::setCurrentIndex(int index, Qt::FocusReason reason)
1363{
1364 Q_Q(QQuickMenu);
1365 if (currentIndex == index)
1366 return;
1367
1368 QQuickMenuItem *newCurrentItem = qobject_cast<QQuickMenuItem *>(itemAt(index));
1369 if (currentItem != newCurrentItem) {
1370 stopHoverTimer();
1371 if (currentItem) {
1372 currentItem->setHighlighted(false);
1373 if (!newCurrentItem && window) {
1374 QQuickItem *focusItem = QQuickItemPrivate::get(contentItem)->subFocusItem;
1375 if (focusItem) {
1376 auto *daPriv = QQuickWindowPrivate::get(window)->deliveryAgentPrivate();
1377 daPriv->clearFocusInScope(contentItem, focusItem, Qt::OtherFocusReason);
1378 }
1379 }
1380 }
1381 if (newCurrentItem) {
1382 newCurrentItem->setHighlighted(true);
1383 newCurrentItem->forceActiveFocus(reason);
1384 }
1385 currentItem = newCurrentItem;
1386 }
1387
1388 currentIndex = index;
1389 emit q->currentIndexChanged();
1390}
1391
1392bool QQuickMenuPrivate::activateNextItem()
1393{
1394 int index = currentIndex;
1395 int count = contentModel->count();
1396 while (++index < count) {
1397 QQuickItem *item = itemAt(index);
1398 if (!item || !item->activeFocusOnTab() || !item->isEnabled())
1399 continue;
1400 setCurrentIndex(index, Qt::TabFocusReason);
1401 return true;
1402 }
1403 return false;
1404}
1405
1406bool QQuickMenuPrivate::activatePreviousItem()
1407{
1408 int index = currentIndex;
1409 while (--index >= 0) {
1410 QQuickItem *item = itemAt(index);
1411 if (!item || !item->activeFocusOnTab() || !item->isEnabled())
1412 continue;
1413 setCurrentIndex(index, Qt::BacktabFocusReason);
1414 return true;
1415 }
1416 return false;
1417}
1418
1419QQuickMenuItem *QQuickMenuPrivate::firstEnabledMenuItem() const
1420{
1421 for (int i = 0; i < contentModel->count(); ++i) {
1422 QQuickItem *item = itemAt(i);
1423 if (!item || !item->isEnabled())
1424 continue;
1425
1426 QQuickMenuItem *menuItem = qobject_cast<QQuickMenuItem *>(item);
1427 if (!menuItem)
1428 continue;
1429
1430 return menuItem;
1431 }
1432 return nullptr;
1433}
1434
1435void QQuickMenuPrivate::contentData_append(QQmlListProperty<QObject> *prop, QObject *obj)
1436{
1437 QQuickMenu *q = qobject_cast<QQuickMenu *>(prop->object);
1438 QQuickMenuPrivate *p = QQuickMenuPrivate::get(q);
1439
1440 QQuickItem *item = qobject_cast<QQuickItem *>(obj);
1441 if (!item) {
1442 if (QQuickAction *action = qobject_cast<QQuickAction *>(obj))
1443 item = p->createItem(action);
1444 else if (QQuickMenu *menu = qobject_cast<QQuickMenu *>(obj))
1445 item = p->createItem(menu);
1446 }
1447
1448 if (item) {
1449 if (QQuickItemPrivate::get(item)->isTransparentForPositioner()) {
1450 QQuickItemPrivate::get(item)->addItemChangeListener(p, QQuickItemPrivate::SiblingOrder);
1451 item->setParentItem(p->contentItem);
1452 } else if (p->contentModel->indexOf(item, nullptr) == -1) {
1453 q->addItem(item);
1454 }
1455 } else {
1456 p->contentData.append(obj);
1457 }
1458}
1459
1460qsizetype QQuickMenuPrivate::contentData_count(QQmlListProperty<QObject> *prop)
1461{
1462 QQuickMenu *q = static_cast<QQuickMenu *>(prop->object);
1463 return QQuickMenuPrivate::get(q)->contentData.size();
1464}
1465
1466QObject *QQuickMenuPrivate::contentData_at(QQmlListProperty<QObject> *prop, qsizetype index)
1467{
1468 QQuickMenu *q = static_cast<QQuickMenu *>(prop->object);
1469 return QQuickMenuPrivate::get(q)->contentData.value(index);
1470}
1471
1472QPalette QQuickMenuPrivate::defaultPalette() const
1473{
1474 return QQuickTheme::palette(QQuickTheme::Menu);
1475}
1476
1477void QQuickMenuPrivate::contentData_clear(QQmlListProperty<QObject> *prop)
1478{
1479 QQuickMenu *q = static_cast<QQuickMenu *>(prop->object);
1480 QQuickMenuPrivate::get(q)->contentData.clear();
1481}
1482
1483void QQuickMenuPrivate::resetContentItem()
1484{
1485 if (contentItem) {
1486 QQuickItemPrivate::get(contentItem)->removeItemChangeListener(this, QQuickItemPrivate::Children);
1487 QQuickItemPrivate::get(contentItem)->removeItemChangeListener(this, QQuickItemPrivate::Destroyed);
1488 QQuickItemPrivate::get(contentItem)->removeItemChangeListener(this, QQuickItemPrivate::Geometry);
1489
1490 const auto children = contentItem->childItems();
1491 for (QQuickItem *child : std::as_const(children))
1492 QQuickItemPrivate::get(child)->removeItemChangeListener(this, QQuickItemPrivate::SiblingOrder);
1493 contentItem = nullptr;
1494 }
1495}
1496
1497QQuickMenu::QQuickMenu(QObject *parent)
1498 : QQuickPopup(*(new QQuickMenuPrivate), parent)
1499{
1500 Q_D(QQuickMenu);
1501 setFocus(true);
1502 d->init();
1503 connect(d->contentModel, &QQmlObjectModel::countChanged, this, &QQuickMenu::countChanged);
1504}
1505
1506QQuickMenu::~QQuickMenu()
1507{
1508 Q_D(QQuickMenu);
1509 qCDebug(lcNativeMenus) << "destroying" << this
1510 << "item count:"
1511 << d->contentModel->count()
1512 << "native item count:" << d->nativeItems.count();
1513 // It would be better to reset the sub-menu within the menu-item during its destruction
1514 // as there can be a chance that the parent menu use invalid reference leading to
1515 // application crash (as mentioned in the bug report QTBUG-137160)
1516 if (auto *menuItem = qobject_cast<QQuickMenuItem *>(d->parentItem)) {
1517 if (menuItem->subMenu() == this) {
1518 auto *menuItemPriv = QQuickMenuItemPrivate::get(menuItem);
1519 menuItemPriv->setSubMenu(nullptr);
1520 }
1521 }
1522 // We have to remove items to ensure that our change listeners on the item
1523 // are removed. It's too late to do this in ~QQuickMenuPrivate, as
1524 // contentModel has already been destroyed before that is called.
1525 // Destruction isn't necessary for the QQuickItems themselves, but it is
1526 // required for the native menus (see comment in removeItem()).
1527 while (d->contentModel->count() > 0)
1528 d->removeItem(0, d->itemAt(0), QQuickMenuPrivate::DestructionPolicy::Destroy);
1529
1530 d->resetContentItem();
1531}
1532
1533/*!
1534 \qmlmethod Item QtQuick.Controls::Menu::itemAt(int index)
1535
1536 Returns the item at \a index, or \c null if it does not exist.
1537*/
1538QQuickItem *QQuickMenu::itemAt(int index) const
1539{
1540 Q_D(const QQuickMenu);
1541 return d->itemAt(index);
1542}
1543
1544/*!
1545 \qmlmethod void QtQuick.Controls::Menu::addItem(Item item)
1546
1547 Adds \a item to the end of the list of items. The menu does not take
1548 ownership of the newly added \a item.
1549
1550 \sa {Dynamically Generating Menu Items}
1551*/
1552void QQuickMenu::addItem(QQuickItem *item)
1553{
1554 Q_D(QQuickMenu);
1555 insertItem(d->contentModel->count(), item);
1556}
1557
1558/*!
1559 \qmlmethod void QtQuick.Controls::Menu::insertItem(int index, Item item)
1560
1561 Inserts \a item at \a index. The menu does not take ownership of the newly
1562 inserted \a item.
1563
1564 \sa {Dynamically Generating Menu Items}
1565*/
1566void QQuickMenu::insertItem(int index, QQuickItem *item)
1567{
1568 Q_D(QQuickMenu);
1569 if (!item)
1570 return;
1571 const int count = d->contentModel->count();
1572 if (index < 0 || index > count)
1573 index = count;
1574
1575 int oldIndex = d->contentModel->indexOf(item, nullptr);
1576 if (oldIndex != -1) {
1577 if (oldIndex < index)
1578 --index;
1579 if (oldIndex != index) {
1580 d->moveItem(oldIndex, index);
1581 }
1582 } else {
1583 d->insertItem(index, item);
1584 }
1585}
1586
1587/*!
1588 \qmlmethod void QtQuick.Controls::Menu::moveItem(int from, int to)
1589
1590 Moves an item \a from one index \a to another.
1591*/
1592void QQuickMenu::moveItem(int from, int to)
1593{
1594 Q_D(QQuickMenu);
1595 const int count = d->contentModel->count();
1596 if (from < 0 || from > count - 1)
1597 return;
1598 if (to < 0 || to > count - 1)
1599 to = count - 1;
1600
1601 if (from != to)
1602 d->moveItem(from, to);
1603}
1604
1605/*!
1606 \since QtQuick.Controls 2.3 (Qt 5.10)
1607 \qmlmethod void QtQuick.Controls::Menu::removeItem(Item item)
1608
1609 Removes and destroys the specified \a item.
1610*/
1611void QQuickMenu::removeItem(QQuickItem *item)
1612{
1613 Q_D(QQuickMenu);
1614 if (!item)
1615 return;
1616
1617 const int index = d->contentModel->indexOf(item, nullptr);
1618 if (index == -1)
1619 return;
1620
1621 d->removeItem(index, item, QQuickMenuPrivate::DestructionPolicy::Destroy);
1622}
1623
1624/*!
1625 \since QtQuick.Controls 2.3 (Qt 5.10)
1626 \qmlmethod MenuItem QtQuick.Controls::Menu::takeItem(int index)
1627
1628 Removes and returns the item at \a index.
1629
1630 \note The ownership of the item is transferred to the caller.
1631*/
1632QQuickItem *QQuickMenu::takeItem(int index)
1633{
1634 Q_D(QQuickMenu);
1635 const int count = d->contentModel->count();
1636 if (index < 0 || index >= count)
1637 return nullptr;
1638
1639 QQuickItem *item = itemAt(index);
1640 if (item)
1641 d->removeItem(index, item);
1642 return item;
1643}
1644
1645/*!
1646 \since QtQuick.Controls 2.3 (Qt 5.10)
1647 \qmlmethod Menu QtQuick.Controls::Menu::menuAt(int index)
1648
1649 Returns the sub-menu at \a index, or \c null if the index is not valid or
1650 there is no sub-menu at the specified index.
1651*/
1652QQuickMenu *QQuickMenu::menuAt(int index) const
1653{
1654 Q_D(const QQuickMenu);
1655 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(d->itemAt(index));
1656 if (!item)
1657 return nullptr;
1658
1659 return item->subMenu();
1660}
1661
1662/*!
1663 \since QtQuick.Controls 2.3 (Qt 5.10)
1664 \qmlmethod void QtQuick.Controls::Menu::addMenu(Menu menu)
1665
1666 Adds \a menu as a sub-menu to the end of this menu. The menu does not take
1667 ownership of the newly added \a menu.
1668*/
1669void QQuickMenu::addMenu(QQuickMenu *menu)
1670{
1671 Q_D(QQuickMenu);
1672 insertMenu(d->contentModel->count(), menu);
1673}
1674
1675/*!
1676 \since QtQuick.Controls 2.3 (Qt 5.10)
1677 \qmlmethod void QtQuick.Controls::Menu::insertMenu(int index, Menu menu)
1678
1679 Inserts \a menu as a sub-menu at \a index. The index is within all items in
1680 the menu. The menu does not take ownership of the newly inserted \a menu.
1681*/
1682void QQuickMenu::insertMenu(int index, QQuickMenu *menu)
1683{
1684 Q_D(QQuickMenu);
1685 if (!menu)
1686 return;
1687
1688 insertItem(index, d->createItem(menu));
1689}
1690
1691/*!
1692 \since QtQuick.Controls 2.3 (Qt 5.10)
1693 \qmlmethod void QtQuick.Controls::Menu::removeMenu(Menu menu)
1694
1695 Removes and destroys the specified \a menu.
1696*/
1697void QQuickMenu::removeMenu(QQuickMenu *menu)
1698{
1699 Q_D(QQuickMenu);
1700 if (!menu)
1701 return;
1702
1703 const int count = d->contentModel->count();
1704 for (int i = 0; i < count; ++i) {
1705 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(d->itemAt(i));
1706 if (!item || item->subMenu() != menu)
1707 continue;
1708
1709 removeItem(item);
1710 break;
1711 }
1712
1713 menu->deleteLater();
1714}
1715
1716/*!
1717 \since QtQuick.Controls 2.3 (Qt 5.10)
1718 \qmlmethod Menu QtQuick.Controls::Menu::takeMenu(int index)
1719
1720 Removes and returns the menu at \a index. The index is within all items in
1721 the menu.
1722
1723 \note The ownership of the menu is transferred to the caller.
1724*/
1725QQuickMenu *QQuickMenu::takeMenu(int index)
1726{
1727 Q_D(QQuickMenu);
1728 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(d->itemAt(index));
1729 if (!item)
1730 return nullptr;
1731
1732 QQuickMenu *subMenu = item->subMenu();
1733 if (!subMenu)
1734 return nullptr;
1735
1736 d->removeItem(index, item);
1737 item->deleteLater();
1738
1739 return subMenu;
1740}
1741
1742/*!
1743 \since QtQuick.Controls 2.3 (Qt 5.10)
1744 \qmlmethod Action QtQuick.Controls::Menu::actionAt(int index)
1745
1746 Returns the action at \a index, or \c null if the index is not valid or
1747 there is no action at the specified index.
1748*/
1749QQuickAction *QQuickMenu::actionAt(int index) const
1750{
1751 Q_D(const QQuickMenu);
1752 if (!const_cast<QQuickMenuPrivate *>(d)->maybeNativeHandle()) {
1753 QQuickAbstractButton *item = qobject_cast<QQuickAbstractButton *>(d->itemAt(index));
1754 if (!item)
1755 return nullptr;
1756
1757 return item->action();
1758 } else {
1759 if (index < 0 || index >= d->nativeItems.size())
1760 return nullptr;
1761
1762 return d->nativeItems.at(index)->action();
1763 }
1764}
1765
1766/*!
1767 \since QtQuick.Controls 2.3 (Qt 5.10)
1768 \qmlmethod void QtQuick.Controls::Menu::addAction(Action action)
1769
1770 Adds \a action to the end of this menu. The menu does not take ownership of
1771 the newly added \a action.
1772*/
1773void QQuickMenu::addAction(QQuickAction *action)
1774{
1775 Q_D(QQuickMenu);
1776 insertAction(d->contentModel->count(), action);
1777}
1778
1779/*!
1780 \since QtQuick.Controls 2.3 (Qt 5.10)
1781 \qmlmethod void QtQuick.Controls::Menu::insertAction(int index, Action action)
1782
1783 Inserts \a action at \a index. The index is within all items in the menu.
1784 The menu does not take ownership of the newly inserted \a action.
1785*/
1786void QQuickMenu::insertAction(int index, QQuickAction *action)
1787{
1788 Q_D(QQuickMenu);
1789 if (!action)
1790 return;
1791
1792 insertItem(index, d->createItem(action));
1793}
1794
1795/*!
1796 \since QtQuick.Controls 2.3 (Qt 5.10)
1797 \qmlmethod void QtQuick.Controls::Menu::removeAction(Action action)
1798
1799 Removes and destroys the specified \a action.
1800*/
1801void QQuickMenu::removeAction(QQuickAction *action)
1802{
1803 Q_D(QQuickMenu);
1804 if (!action)
1805 return;
1806
1807 const int count = d->contentModel->count();
1808 for (int i = 0; i < count; ++i) {
1809 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(d->itemAt(i));
1810 if (!item || item->action() != action)
1811 continue;
1812
1813 removeItem(item);
1814 break;
1815 }
1816
1817 action->deleteLater();
1818}
1819
1820/*!
1821 \since QtQuick.Controls 2.3 (Qt 5.10)
1822 \qmlmethod Action QtQuick.Controls::Menu::takeAction(int index)
1823
1824 Removes and returns the action at \a index. The index is within all items in
1825 the menu.
1826
1827 \note The ownership of the action is transferred to the caller.
1828*/
1829QQuickAction *QQuickMenu::takeAction(int index)
1830{
1831 Q_D(QQuickMenu);
1832 QQuickMenuItem *item = qobject_cast<QQuickMenuItem *>(d->itemAt(index));
1833 if (!item)
1834 return nullptr;
1835
1836 QQuickAction *action = item->action();
1837 if (!action)
1838 return nullptr;
1839
1840 d->removeItem(index, item);
1841 item->deleteLater();
1842 return action;
1843}
1844
1845bool QQuickMenu::isVisible() const
1846{
1847 Q_D(const QQuickMenu);
1848 if (d->maybeNativeHandle())
1849 return d->visible;
1850 return QQuickPopup::isVisible();
1851}
1852
1853void QQuickMenu::setVisible(bool visible)
1854{
1855 Q_D(QQuickMenu);
1856 if (visible == d->visible)
1857 return;
1858
1859 auto *window = this->window();
1860 if (visible && window) {
1861 // If a right mouse button event opens a menu, don't synthesize QContextMenuEvent
1862 // (avoid opening redundant menus, e.g. in parent items).
1863 QQuickWindowPrivate::get(window)->rmbContextMenuEventEnabled = false;
1864 // Also, if users have their own custom non-ContextMenu-based text editing context menus,
1865 // we want those to take priority over our own. The check above handles that when
1866 // the user opens their menu on press, but not on release. For that, we close all
1867 // other menus that are open, assuming that we're not a sub-menu.
1868 if (!d->parentMenu) {
1869 QQuickOverlay *overlay = QQuickOverlay::overlay(window, parentItem());
1870 if (overlay) {
1871 const QList<QQuickPopup *> allPopups = QQuickOverlayPrivate::get(overlay)->allPopups;
1872 for (auto *popup : allPopups) {
1873 if (popup != this && qobject_cast<QQuickMenu *>(popup))
1874 popup->close();
1875 }
1876 }
1877 }
1878 }
1879
1880 if (visible && ((d->useNativeMenu() && !d->maybeNativeHandle())
1881 || (!d->useNativeMenu() && d->maybeNativeHandle()))) {
1882 // We've been made visible, and our actual native state doesn't match our requested state,
1883 // which means AA_DontUseNativeMenuWindows was set while we were visible or had a parent.
1884 // Try to sync our state again now that we're about to be re-opened.
1885 qCDebug(lcNativeMenus) << "setVisible called - useNativeMenu:" << d->useNativeMenu()
1886 << "maybeNativeHandle:" << d->maybeNativeHandle();
1887 d->syncWithUseNativeMenu();
1888 }
1889 if (d->maybeNativeHandle()) {
1890 d->setNativeMenuVisible(visible);
1891 return;
1892 }
1893
1894#if QT_CONFIG(xcb)
1895 if (QQuickMenuPrivate::get(d->rootMenu())->menuBar)
1896 d->wmWindowType = QNativeInterface::Private::QXcbWindow::DropDownMenu;
1897 else
1898 d->wmWindowType = QNativeInterface::Private::QXcbWindow::PopupMenu;
1899#endif
1900
1901 // Either the native menu wasn't wanted, or it couldn't be created;
1902 // show the non-native menu.
1903 QQuickPopup::setVisible(visible);
1904}
1905
1906/*!
1907 \qmlproperty model QtQuick.Controls::Menu::contentModel
1908 \readonly
1909
1910 This property holds the model used to display menu items.
1911
1912 The content model is provided for visualization purposes. It can be assigned
1913 as a model to a content item that presents the contents of the menu.
1914
1915 \code
1916 Menu {
1917 id: menu
1918 contentItem: ListView {
1919 model: menu.contentModel
1920 }
1921 }
1922 \endcode
1923
1924 The model allows menu items to be statically declared as children of the
1925 menu.
1926*/
1927QVariant QQuickMenu::contentModel() const
1928{
1929 Q_D(const QQuickMenu);
1930 return QVariant::fromValue(d->contentModel);
1931}
1932
1933/*!
1934 \qmlproperty list<QtObject> QtQuick.Controls::Menu::contentData
1935 \qmldefault
1936
1937 This property holds the list of content data.
1938
1939 The list contains all objects that have been declared in QML as children
1940 of the menu, and also items that have been dynamically added or
1941 inserted using the \l addItem() and \l insertItem() methods, respectively.
1942
1943 \note Unlike \c contentChildren, \c contentData does include non-visual QML
1944 objects. It is not re-ordered when items are inserted or moved.
1945
1946 \sa Item::data, {Popup::}{contentChildren}
1947*/
1948QQmlListProperty<QObject> QQuickMenu::contentData()
1949{
1950 Q_D(QQuickMenu);
1951 if (!d->contentItem)
1952 QQuickControlPrivate::get(d->popupItem)->executeContentItem();
1953 return QQmlListProperty<QObject>(this, nullptr,
1954 QQuickMenuPrivate::contentData_append,
1955 QQuickMenuPrivate::contentData_count,
1956 QQuickMenuPrivate::contentData_at,
1957 QQuickMenuPrivate::contentData_clear);
1958}
1959
1960/*!
1961 \qmlproperty string QtQuick.Controls::Menu::title
1962
1963 This property holds the title for the menu.
1964
1965 The title of a menu is often displayed in the text of a menu item when the
1966 menu is a submenu, and in the text of a tool button when it is in a
1967 menubar.
1968*/
1969QString QQuickMenu::title() const
1970{
1971 Q_D(const QQuickMenu);
1972 return d->title;
1973}
1974
1975void QQuickMenu::setTitle(const QString &title)
1976{
1977 Q_D(QQuickMenu);
1978 if (title == d->title)
1979 return;
1980 d->title = title;
1981 if (d->handle)
1982 d->handle->setText(title);
1983 emit titleChanged(title);
1984}
1985
1986/*!
1987 \qmlproperty string QtQuick.Controls::Menu::icon.name
1988 \qmlproperty url QtQuick.Controls::Menu::icon.source
1989 \qmlproperty int QtQuick.Controls::Menu::icon.width
1990 \qmlproperty int QtQuick.Controls::Menu::icon.height
1991 \qmlproperty color QtQuick.Controls::Menu::icon.color
1992 \qmlproperty bool QtQuick.Controls::Menu::icon.cache
1993
1994 \since QtQuick.Controls 6.5
1995
1996 \include qquickicon.qdocinc grouped-properties
1997
1998 \include qquickmenu.qdocinc non-native-only-property
1999
2000 \sa AbstractButton::text, AbstractButton::display, {Icons in Qt Quick Controls}
2001*/
2002
2003QQuickIcon QQuickMenu::icon() const
2004{
2005 Q_D(const QQuickMenu);
2006 return d->icon;
2007}
2008
2009void QQuickMenu::setIcon(const QQuickIcon &icon)
2010{
2011 Q_D(QQuickMenu);
2012 if (icon == d->icon)
2013 return;
2014 d->icon = icon;
2015 d->icon.ensureRelativeSourceResolved(this);
2016 emit iconChanged(icon);
2017}
2018
2019/*!
2020 \since QtQuick.Controls 6.12 (Qt 6.12)
2021 \qmlproperty bool QtQuick.Controls::Menu::separatorsCollapsible
2022
2023 This property holds whether consecutive separators should be collapsed.
2024
2025 When this property is \c true, the menu will automatically
2026 hide separators that would appear at the beginning or end of the visible
2027 items, as well as consecutive separators where all items between them are
2028 hidden. This mirrors the behavior of \l QMenu::separatorsCollapsible in
2029 Qt Widgets.
2030
2031 The default value is \c true.
2032
2033 This is useful when menu items are dynamically shown or hidden, as it
2034 prevents orphaned separators from being displayed.
2035
2036 \note Separators that have a user-defined binding on the \l {Item::}{visible}
2037 property are not affected by this mechanism and are left unchanged.
2038 For separators without a \c visible binding, the menu manages both
2039 \l {Item::}{visible} and \l {Item::}{height} properties. Any existing
2040 binding on \l {Item::}{height} will be overwritten.
2041
2042 \sa MenuSeparator
2043*/
2044bool QQuickMenu::separatorsCollapsible() const
2045{
2046 Q_D(const QQuickMenu);
2047 return d->collapsibleSeparators;
2048}
2049
2050void QQuickMenu::setSeparatorsCollapsible(bool collapsible)
2051{
2052 Q_D(QQuickMenu);
2053 if (d->collapsibleSeparators == collapsible)
2054 return;
2055 d->collapsibleSeparators = collapsible;
2056 emit separatorsCollapsibleChanged();
2057 d->updateCollapsedSeparators();
2058 if (d->handle)
2059 d->handle->syncSeparatorsCollapsible(collapsible);
2060}
2061
2062/*!
2063 \since QtQuick.Controls 2.3 (Qt 5.10)
2064 \qmlproperty bool QtQuick.Controls::Menu::cascade
2065
2066 This property holds whether the menu cascades its sub-menus.
2067
2068 The default value is platform-specific. Menus are cascading by default on
2069 desktop platforms that have a mouse cursor available. Non-cascading menus
2070 are shown one menu at a time, and centered over the parent menu.
2071
2072 \note Changing the value of the property has no effect while the menu is open.
2073
2074 \include qquickmenu.qdocinc non-native-only-property
2075
2076 \sa overlap
2077*/
2078bool QQuickMenu::cascade() const
2079{
2080 Q_D(const QQuickMenu);
2081 return d->cascade;
2082}
2083
2084void QQuickMenu::setCascade(bool cascade)
2085{
2086 Q_D(QQuickMenu);
2087 if (d->cascade == cascade)
2088 return;
2089 d->cascade = cascade;
2090 if (d->parentMenu)
2091 d->resolveParentItem();
2092 emit cascadeChanged(cascade);
2093}
2094
2095void QQuickMenu::resetCascade()
2096{
2097 Q_D(QQuickMenu);
2098 if (d->parentMenu)
2099 setCascade(d->parentMenu->cascade());
2100 else
2101 setCascade(shouldCascade());
2102}
2103
2104/*!
2105 \since QtQuick.Controls 2.3 (Qt 5.10)
2106 \qmlproperty real QtQuick.Controls::Menu::overlap
2107
2108 This property holds the amount of pixels by which the menu horizontally overlaps its parent menu.
2109
2110 The property only has effect when the menu is used as a cascading sub-menu.
2111
2112 The default value is style-specific.
2113
2114 \note Changing the value of the property has no effect while the menu is open.
2115
2116 \include qquickmenu.qdocinc non-native-only-property
2117
2118 \sa cascade
2119*/
2120qreal QQuickMenu::overlap() const
2121{
2122 Q_D(const QQuickMenu);
2123 return d->overlap;
2124}
2125
2126void QQuickMenu::setOverlap(qreal overlap)
2127{
2128 Q_D(QQuickMenu);
2129 if (d->overlap == overlap)
2130 return;
2131 d->overlap = overlap;
2132 emit overlapChanged();
2133}
2134
2135/*!
2136 \since QtQuick.Controls 2.3 (Qt 5.10)
2137 \qmlproperty Component QtQuick.Controls::Menu::delegate
2138
2139 This property holds the component that is used to create items
2140 to present actions.
2141
2142 \code
2143 Menu {
2144 Action { text: "Cut" }
2145 Action { text: "Copy" }
2146 Action { text: "Paste" }
2147 }
2148 \endcode
2149
2150 \note delegates will only be visible when using a \l {Menu types}
2151 {non-native Menu}.
2152
2153 \include delegate-ownership.qdocinc {no-ownership} {Menu}
2154
2155 \sa Action
2156*/
2157QQmlComponent *QQuickMenu::delegate() const
2158{
2159 Q_D(const QQuickMenu);
2160 return d->delegate;
2161}
2162
2163void QQuickMenu::setDelegate(QQmlComponent *delegate)
2164{
2165 Q_D(QQuickMenu);
2166 if (d->delegate == delegate)
2167 return;
2168
2169 d->delegate = delegate;
2170 emit delegateChanged();
2171}
2172
2173/*!
2174 \since QtQuick.Controls 2.3 (Qt 5.10)
2175 \qmlproperty int QtQuick.Controls::Menu::currentIndex
2176
2177 This property holds the index of the currently highlighted item.
2178
2179 Menu items can be highlighted by mouse hover or keyboard navigation.
2180
2181 \include qquickmenu.qdocinc non-native-only-property
2182
2183 \sa MenuItem::highlighted
2184*/
2185int QQuickMenu::currentIndex() const
2186{
2187 Q_D(const QQuickMenu);
2188 return d->currentIndex;
2189}
2190
2191void QQuickMenu::setCurrentIndex(int index)
2192{
2193 Q_D(QQuickMenu);
2194 d->setCurrentIndex(index, Qt::OtherFocusReason);
2195}
2196
2197/*!
2198 \since QtQuick.Controls 2.3 (Qt 5.10)
2199 \qmlproperty int QtQuick.Controls::Menu::count
2200 \readonly
2201
2202 This property holds the number of items.
2203*/
2204int QQuickMenu::count() const
2205{
2206 Q_D(const QQuickMenu);
2207 return d->contentModel->count();
2208}
2209
2210void QQuickMenuPrivate::popup(QQuickItem *menuItem)
2211{
2212 Q_Q(QQuickMenu);
2213 // No position has been explicitly specified, so position the menu at the mouse cursor
2214 // on desktop platforms that have a mouse cursor available and support multiple windows.
2215 QQmlNullableValue<QPointF> pos;
2216#if QT_CONFIG(cursor)
2217 if (parentItem && QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::MultipleWindows))
2218 pos = parentItem->mapFromGlobal(QCursor::pos());
2219#endif
2220
2221 // As a fallback, center the menu over its parent item.
2222 if (!pos.isValid() && parentItem)
2223 pos = QPointF((parentItem->width() - q->width()) / 2, (parentItem->height() - q->height()) / 2);
2224
2225 q->popup(pos.isValid() ? pos.value() : QPointF(), menuItem);
2226}
2227
2228void QQuickMenu::popup(const QPointF &position, QQuickItem *menuItem)
2229{
2230 Q_D(QQuickMenu);
2231 qreal offset = 0;
2232#if QT_CONFIG(cursor)
2233 if (menuItem)
2234 offset = d->popupItem->mapFromItem(menuItem, QPointF(0, 0)).y();
2235#endif
2236 setPosition(position - QPointF(0, offset));
2237
2238 if (menuItem)
2239 d->setCurrentIndex(d->contentModel->indexOf(menuItem, nullptr), Qt::PopupFocusReason);
2240 else
2241 d->setCurrentIndex(-1, Qt::PopupFocusReason);
2242
2243 open();
2244}
2245
2246/*!
2247 \since QtQuick.Controls 2.3 (Qt 5.10)
2248 \qmlmethod void QtQuick.Controls::Menu::popup(MenuItem item = null)
2249 \qmlmethod void QtQuick.Controls::Menu::popup(Item parent, MenuItem item = null)
2250
2251 Opens the menu at the mouse cursor on desktop platforms that have a mouse cursor
2252 available, and otherwise centers the menu over its \a parent item.
2253
2254 The menu can be optionally aligned to a specific menu \a item. This item will
2255 then become \l {currentIndex}{current.} If no \a item is specified, \l currentIndex
2256 will be set to \c -1.
2257
2258 \sa Popup::open()
2259*/
2260
2261/*!
2262 \since QtQuick.Controls 2.3 (Qt 5.10)
2263 \qmlmethod void QtQuick.Controls::Menu::popup(point pos, MenuItem item = null)
2264 \qmlmethod void QtQuick.Controls::Menu::popup(Item parent, point pos, MenuItem item = null)
2265
2266 Opens the menu at the specified position \a pos in the popups coordinate system,
2267 that is, a coordinate relative to its \a parent item.
2268
2269 The menu can be optionally aligned to a specific menu \a item. This item will
2270 then become \l {currentIndex}{current.} If no \a item is specified, \l currentIndex
2271 will be set to \c -1.
2272
2273 \sa Popup::open()
2274*/
2275
2276/*!
2277 \since QtQuick.Controls 2.3 (Qt 5.10)
2278 \qmlmethod void QtQuick.Controls::Menu::popup(real x, real y, MenuItem item = null)
2279 \qmlmethod void QtQuick.Controls::Menu::popup(Item parent, real x, real y, MenuItem item = null)
2280
2281 Opens the menu at the specified position \a x, \a y in the popups coordinate system,
2282 that is, a coordinate relative to its \a parent item.
2283
2284 The menu can be optionally aligned to a specific menu \a item. This item will
2285 then become \l {currentIndex}{current.} If no \a item is specified, \l currentIndex
2286 will be set to \c -1.
2287
2288 \sa dismiss(), Popup::open()
2289*/
2290
2291void QQuickMenu::popup(QQuickItem *parent, qreal x, qreal y, QQuickItem *menuItem)
2292{
2293 popup(parent, QPointF {x, y}, menuItem);
2294}
2295
2296void QQuickMenu::popup(QQuickItem *parent, const QPointF &position, QQuickItem *menuItem)
2297{
2298 Q_D(QQuickMenu);
2299 if (parent && !d->popupItem->isAncestorOf(parent))
2300 setParentItem(parent);
2301 popup(position, menuItem);
2302}
2303
2304void QQuickMenu::popup(QQuickItem *parent, QQuickItem *menuItem)
2305{
2306 Q_D(QQuickMenu);
2307 QQuickItem *parentItem = nullptr;
2308 if (parent && !d->popupItem->isAncestorOf(parent))
2309 parentItem = parent;
2310 if (parentItem)
2311 setParentItem(parentItem);
2312 d->popup(menuItem);
2313}
2314
2315// if a single argument is given, it is treated as both the parent _and_ the menu item
2316// note: This differs from QQuickMenuPrivate::popup, which doesn't do parent handling
2317void QQuickMenu::popup(QQuickItem *parent)
2318{
2319 Q_D(QQuickMenu);
2320 QQuickItem *menuItem = nullptr;
2321 if (parent) {
2322 if (!d->popupItem->isAncestorOf(parent))
2323 setParentItem(parent);
2324 if (d->popupItem->isAncestorOf(parent))
2325 menuItem = parent;
2326 }
2327 d->popup(menuItem);
2328}
2329
2330void QQuickMenu::popup(qreal x, qreal y, QQuickItem *menuItem)
2331{
2332 popup(QPointF {x, y}, menuItem);
2333}
2334
2335/*!
2336 \since QtQuick.Controls 2.3 (Qt 5.10)
2337 \qmlmethod void QtQuick.Controls::Menu::dismiss()
2338
2339 Closes all menus in the hierarchy that this menu belongs to.
2340
2341 \note Unlike \l {Popup::}{close()} that only closes a menu and its
2342 sub-menus (when using \l {Menu types}{non-native menus}), \c dismiss()
2343 closes the whole hierarchy of menus, including the parent menus. In
2344 practice, \c close() is suitable e.g. for implementing navigation in a
2345 hierarchy of menus, and \c dismiss() is the appropriate method for closing
2346 the whole hierarchy of menus.
2347
2348 \sa popup(), Popup::close()
2349*/
2350void QQuickMenu::dismiss()
2351{
2352 QQuickMenu *menu = this;
2353 while (menu) {
2354 menu->close();
2355 menu = QQuickMenuPrivate::get(menu)->parentMenu;
2356 }
2357}
2358
2359void QQuickMenu::componentComplete()
2360{
2361 Q_D(QQuickMenu);
2362 QQuickPopup::componentComplete();
2363 d->resizeItems();
2364 d->updateTextPadding();
2365 d->syncWithUseNativeMenu();
2366}
2367
2368void QQuickMenu::contentItemChange(QQuickItem *newItem, QQuickItem *oldItem)
2369{
2370 Q_D(QQuickMenu);
2371 QQuickPopup::contentItemChange(newItem, oldItem);
2372
2373 if (oldItem) {
2374 QQuickItemPrivate::get(oldItem)->removeItemChangeListener(d, QQuickItemPrivate::Children);
2375 QQuickItemPrivate::get(oldItem)->removeItemChangeListener(d, QQuickItemPrivate::Destroyed);
2376 QQuickItemPrivate::get(oldItem)->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
2377 }
2378 if (newItem) {
2379 QQuickItemPrivate::get(newItem)->addItemChangeListener(d, QQuickItemPrivate::Children);
2380 QQuickItemPrivate::get(newItem)->addItemChangeListener(d, QQuickItemPrivate::Destroyed);
2381 QQuickItemPrivate::get(newItem)->updateOrAddGeometryChangeListener(d, QQuickGeometryChange::Width);
2382 }
2383
2384 d->contentItem = newItem;
2385}
2386
2387void QQuickMenu::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &data)
2388{
2389 Q_D(QQuickMenu);
2390 QQuickPopup::itemChange(change, data);
2391
2392 switch (change) {
2393 case QQuickItem::ItemVisibleHasChanged:
2394 if (!data.boolValue && d->cascade) {
2395 // Ensure that when the menu isn't visible, there's no current item
2396 // the next time it's opened.
2397 d->setCurrentIndex(-1, Qt::OtherFocusReason);
2398 }
2399 break;
2400 default:
2401 break;
2402 }
2403}
2404
2405void QQuickMenu::keyPressEvent(QKeyEvent *event)
2406{
2407 Q_D(QQuickMenu);
2408 QQuickPopup::keyPressEvent(event);
2409
2410 // QTBUG-17051
2411 // Work around the fact that ListView has no way of distinguishing between
2412 // mouse and keyboard interaction, thanks to the "interactive" bool in Flickable.
2413 // What we actually want is to have a way to always allow keyboard interaction but
2414 // only allow flicking with the mouse when there are too many menu items to be
2415 // shown at once.
2416 switch (event->key()) {
2417 case Qt::Key_Up:
2418 if (!d->activatePreviousItem())
2419 d->propagateKeyEvent(event);
2420 break;
2421
2422 case Qt::Key_Down:
2423 d->activateNextItem();
2424 break;
2425
2426 case Qt::Key_Left:
2427 case Qt::Key_Right:
2428 event->ignore();
2429 if (d->popupItem->isMirrored() == (event->key() == Qt::Key_Right)) {
2430 if (d->parentMenu && d->currentItem) {
2431 if (!d->cascade)
2432 d->parentMenu->open();
2433 close();
2434 event->accept();
2435 }
2436 } else {
2437 if (QQuickMenu *subMenu = d->currentSubMenu()) {
2438 auto subMenuPrivate = QQuickMenuPrivate::get(subMenu);
2439 subMenuPrivate->popup(subMenuPrivate->firstEnabledMenuItem());
2440 event->accept();
2441 }
2442 }
2443 if (!event->isAccepted())
2444 d->propagateKeyEvent(event);
2445 break;
2446
2447#if QT_CONFIG(shortcut)
2448 case Qt::Key_Alt:
2449 // If &mnemonic shortcut is enabled, go back to (possibly) the parent
2450 // menu bar so the shortcut key will be processed by the menu bar.
2451 if (!QKeySequence::mnemonic(QStringLiteral("&A")).isEmpty())
2452 close();
2453 break;
2454#endif
2455
2456 default:
2457 break;
2458 }
2459
2460#if QT_CONFIG(shortcut)
2461 if (event->modifiers() == Qt::NoModifier) {
2462 for (int i = 0; i < count(); ++i) {
2463 QQuickAbstractButton *item = qobject_cast<QQuickAbstractButton*>(d->itemAt(i));
2464 if (!item)
2465 continue;
2466 const QKeySequence keySequence = QKeySequence::mnemonic(item->text());
2467 if (keySequence.isEmpty())
2468 continue;
2469 if (keySequence[0].key() == event->key()) {
2470 item->click();
2471 break;
2472 }
2473 }
2474 }
2475#endif
2476}
2477
2478void QQuickMenu::timerEvent(QTimerEvent *event)
2479{
2480 Q_D(QQuickMenu);
2481 if (event->timerId() == d->hoverTimer) {
2482 if (QQuickMenu *subMenu = d->currentSubMenu())
2483 subMenu->open();
2484 d->stopHoverTimer();
2485 return;
2486 }
2487 QQuickPopup::timerEvent(event);
2488}
2489
2490QFont QQuickMenu::defaultFont() const
2491{
2492 return QQuickTheme::font(QQuickTheme::Menu);
2493}
2494
2495#if QT_CONFIG(accessibility)
2496QAccessible::Role QQuickMenu::accessibleRole() const
2497{
2498 return QAccessible::PopupMenu;
2499}
2500#endif
2501
2502QT_END_NAMESPACE
2503
2504#include "moc_qquickmenu_p.cpp"
QQuickMenuPositioner(QQuickMenu *menu)
void reposition() override
Combined button and popup list for selecting options.
static const QQuickPopup::ClosePolicy cascadingSubMenuClosePolicy
Menu popup that can be used as a context menu or popup menu.
static QQuickItem * findParentMenuItem(QQuickMenu *subMenu)
static bool shouldCascade()
QString nativeMenuItemListToString(const QList< QQuickNativeMenuItem * > &nativeItems)