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
qabstractitemview.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
6
7#include <qpointer.h>
8#include <qapplication.h>
9#include <qclipboard.h>
10#include <qpainter.h>
11#include <qstyle.h>
12#if QT_CONFIG(draganddrop)
13#include <qdrag.h>
14#endif
15#include <qevent.h>
16#include <qscrollbar.h>
17#if QT_CONFIG(tooltip)
18#include <qtooltip.h>
19#endif
20#include <qdatetime.h>
21#if QT_CONFIG(lineedit)
22#include <qlineedit.h>
23#endif
24#if QT_CONFIG(spinbox)
25#include <qspinbox.h>
26#endif
27#include <qheaderview.h>
28#include <qstyleditemdelegate.h>
29#include <private/qabstractitemview_p.h>
30#include <private/qabstractitemmodel_p.h>
31#include <private/qapplication_p.h>
32#include <private/qguiapplication_p.h>
33#include <private/qscrollbar_p.h>
34#if QT_CONFIG(accessibility)
35#include <qaccessible.h>
36#endif
37#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
38# include <qscroller.h>
39#endif
40
41#include <algorithm>
42
44Q_STATIC_LOGGING_CATEGORY(lcAIV, "qt.widgets.abtractitemview");
45
46QAbstractItemViewPrivate::QAbstractItemViewPrivate()
47 : model(QAbstractItemModelPrivate::staticEmptyModel()),
48 itemDelegate(nullptr),
49 selectionModel(nullptr),
50 ctrlDragSelectionFlag(QItemSelectionModel::NoUpdate),
51 noSelectionOnMousePress(false),
52 selectionMode(QAbstractItemView::ExtendedSelection),
53 selectionBehavior(QAbstractItemView::SelectItems),
54 currentlyCommittingEditor(nullptr),
55 pressClosedEditor(false),
56 waitForIMCommit(false),
57 pressedModifiers(Qt::NoModifier),
58 pressedPosition(QPoint(-1, -1)),
59 pressedAlreadySelected(false),
60 releaseFromDoubleClick(false),
61 viewportEnteredNeeded(false),
62 state(QAbstractItemView::NoState),
63 stateBeforeAnimation(QAbstractItemView::NoState),
64 editTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed),
65 lastTrigger(QAbstractItemView::NoEditTriggers),
66 tabKeyNavigation(false),
67#if QT_CONFIG(draganddrop)
68 showDropIndicator(true),
69 dragEnabled(false),
70 dragDropMode(QAbstractItemView::NoDragDrop),
71 overwrite(false),
72 dropEventMoved(false),
73 dropIndicatorPosition(QAbstractItemView::OnItem),
74 defaultDropAction(Qt::IgnoreAction),
75#endif
76 autoScroll(true),
77 autoScrollMargin(16),
78 autoScrollCount(0),
79 shouldScrollToCurrentOnShow(false),
80 shouldClearStatusTip(false),
81 alternatingColors(false),
82 textElideMode(Qt::ElideRight),
83 verticalScrollMode(QAbstractItemView::ScrollPerItem),
84 horizontalScrollMode(QAbstractItemView::ScrollPerItem),
85 currentIndexSet(false),
86 wrapItemText(false),
87 delayedPendingLayout(true),
88 moveCursorUpdatedView(false),
89 verticalScrollModeSet(false),
90 horizontalScrollModeSet(false),
91 updateThreshold(200)
92{
93 keyboardInputTime.invalidate();
94}
95
96QAbstractItemViewPrivate::~QAbstractItemViewPrivate()
97{
98}
99
100void QAbstractItemViewPrivate::init()
101{
102 Q_Q(QAbstractItemView);
103 q->setItemDelegate(new QStyledItemDelegate(q));
104
105 vbar->setRange(0, 0);
106 hbar->setRange(0, 0);
107
108 scrollbarConnections = {
109 QObject::connect(vbar, &QScrollBar::actionTriggered,
110 q, &QAbstractItemView::verticalScrollbarAction),
111 QObject::connect(hbar, &QScrollBar::actionTriggered,
112 q, &QAbstractItemView::horizontalScrollbarAction),
113 QObject::connect(vbar, &QScrollBar::valueChanged,
114 q, &QAbstractItemView::verticalScrollbarValueChanged),
115 QObject::connect(hbar, &QScrollBar::valueChanged,
116 q, &QAbstractItemView::horizontalScrollbarValueChanged)
117 };
118 viewport->setBackgroundRole(QPalette::Base);
119
120 q->setAttribute(Qt::WA_InputMethodEnabled);
121
122 verticalScrollMode = static_cast<QAbstractItemView::ScrollMode>(q->style()->styleHint(QStyle::SH_ItemView_ScrollMode, nullptr, q, nullptr));
123 horizontalScrollMode = static_cast<QAbstractItemView::ScrollMode>(q->style()->styleHint(QStyle::SH_ItemView_ScrollMode, nullptr, q, nullptr));
124}
125
126void QAbstractItemViewPrivate::setHoverIndex(const QPersistentModelIndex &index)
127{
128 Q_Q(QAbstractItemView);
129 if (hover == index)
130 return;
131
132 if (selectionBehavior != QAbstractItemView::SelectRows) {
133 q->update(hover); //update the old one
134 q->update(index); //update the new one
135 } else {
136 const QRect oldHoverRect = visualRect(hover);
137 const QRect newHoverRect = visualRect(index);
138 viewport->update(QRect(0, newHoverRect.y(), viewport->width(), newHoverRect.height()));
139 viewport->update(QRect(0, oldHoverRect.y(), viewport->width(), oldHoverRect.height()));
140 }
141 hover = index;
142}
143
144void QAbstractItemViewPrivate::checkMouseMove(const QPersistentModelIndex &index)
145{
146 //we take a persistent model index because the model might change by emitting signals
147 Q_Q(QAbstractItemView);
148 setHoverIndex(index);
149 if (viewportEnteredNeeded || enteredIndex != index) {
150 viewportEnteredNeeded = false;
151
152 if (index.isValid()) {
153 emit q->entered(index);
154#if QT_CONFIG(statustip)
155 QString statustip = model->data(index, Qt::StatusTipRole).toString();
156 if (parent && (shouldClearStatusTip || !statustip.isEmpty())) {
157 QStatusTipEvent tip(statustip);
158 QCoreApplication::sendEvent(parent, &tip);
159 shouldClearStatusTip = !statustip.isEmpty();
160 }
161#endif
162 } else {
163#if QT_CONFIG(statustip)
164 if (parent && shouldClearStatusTip) {
165 QString emptyString;
166 QStatusTipEvent tip( emptyString );
167 QCoreApplication::sendEvent(parent, &tip);
168 }
169#endif
170 emit q->viewportEntered();
171 }
172 enteredIndex = index;
173 }
174}
175
176#if QT_CONFIG(accessibility)
177void QAbstractItemViewPrivate::updateItemAccessibility(const QModelIndex &index,
178 const QList<int> &roles)
179{
180 Q_Q(QAbstractItemView);
181
182 if (!QAccessible::isActive())
183 return;
184
185 const int childIndex = accessibleChildIndex(index);
186 if (childIndex < 0)
187 return;
189 // see QAccessibleTableCell for how role data are mapped to the a11y layer
190
191 for (int role : roles) {
192 if (role == Qt::AccessibleTextRole
193 || (role == Qt::DisplayRole
194 && index.data(Qt::AccessibleTextRole).toString().isEmpty())) {
195 QAccessibleEvent event(q, QAccessible::NameChanged);
196 event.setChild(childIndex);
197 QAccessible::updateAccessibility(&event);
198 } else if (role == Qt::AccessibleDescriptionRole) {
199 QAccessibleEvent event(q, QAccessible::DescriptionChanged);
200 event.setChild(childIndex);
201 QAccessible::updateAccessibility(&event);
202 } else if (role == Qt::CheckStateRole) {
203 QAccessible::State state;
204 state.checked = true;
205 QAccessibleStateChangeEvent event(q, state);
206 event.setChild(childIndex);
207 QAccessible::updateAccessibility(&event);
208 }
209 }
210}
211#endif
212
213#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
214
215// stores and restores the selection and current item when flicking
216void QAbstractItemViewPrivate::scrollerStateChanged()
217{
218 Q_Q(QAbstractItemView);
219
220 if (QScroller *scroller = QScroller::scroller(viewport)) {
221 switch (scroller->state()) {
222 case QScroller::Pressed:
223 // store the current selection in case we start scrolling
224 if (q->selectionModel()) {
225 oldSelection = q->selectionModel()->selection();
226 oldCurrent = q->selectionModel()->currentIndex();
227 }
228 break;
229
230 case QScroller::Dragging:
231 // restore the old selection if we really start scrolling
232 if (q->selectionModel()) {
233 q->selectionModel()->select(oldSelection, QItemSelectionModel::ClearAndSelect);
234 // block autoScroll logic while we are already handling scrolling
235 const bool wasAutoScroll = autoScroll;
236 autoScroll = false;
237 q->selectionModel()->setCurrentIndex(oldCurrent, QItemSelectionModel::NoUpdate);
238 autoScroll = wasAutoScroll;
239 }
240 Q_FALLTHROUGH();
241
242 default:
243 oldSelection = QItemSelection();
244 oldCurrent = QModelIndex();
245 break;
246 }
247 }
248}
249
250#endif // QT_NO_GESTURES
251
252void QAbstractItemViewPrivate::delegateSizeHintChanged(const QModelIndex &index)
253{
254 Q_Q(QAbstractItemView);
255 if (model) {
256 if (!model->checkIndex(index))
257 qCWarning(lcAIV, "Delegate size hint changed for a model index that does not belong to this view");
258 }
259 QMetaObject::invokeMethod(q, &QAbstractItemView::doItemsLayout, Qt::QueuedConnection);
260}
261
262void QAbstractItemViewPrivate::connectDelegate(QAbstractItemDelegate *delegate)
263{
264 if (!delegate)
265 return;
266 Q_Q(QAbstractItemView);
267 QObject::connect(delegate, &QAbstractItemDelegate::closeEditor,
268 q, &QAbstractItemView::closeEditor);
269 QObject::connect(delegate, &QAbstractItemDelegate::commitData,
270 q, &QAbstractItemView::commitData);
271 QObjectPrivate::connect(delegate, &QAbstractItemDelegate::sizeHintChanged,
272 this, &QAbstractItemViewPrivate::delegateSizeHintChanged);
273}
274
275void QAbstractItemViewPrivate::disconnectDelegate(QAbstractItemDelegate *delegate)
276{
277 if (!delegate)
278 return;
279 Q_Q(QAbstractItemView);
280 QObject::disconnect(delegate, &QAbstractItemDelegate::closeEditor,
281 q, &QAbstractItemView::closeEditor);
282 QObject::disconnect(delegate, &QAbstractItemDelegate::commitData,
283 q, &QAbstractItemView::commitData);
284 QObjectPrivate::disconnect(delegate, &QAbstractItemDelegate::sizeHintChanged,
285 this, &QAbstractItemViewPrivate::delegateSizeHintChanged);
286}
287
288void QAbstractItemViewPrivate::disconnectAll()
289{
290 Q_Q(QAbstractItemView);
291 for (QMetaObject::Connection &connection : modelConnections)
292 QObject::disconnect(connection);
293 for (QMetaObject::Connection &connection : scrollbarConnections)
294 QObject::disconnect(connection);
295 disconnectDelegate(itemDelegate);
296 for (QAbstractItemDelegate *delegate : std::as_const(rowDelegates))
297 disconnectDelegate(delegate);
298 for (QAbstractItemDelegate *delegate : std::as_const(columnDelegates))
299 disconnectDelegate(delegate);
300 if (model && selectionModel) {
301 QObject::disconnect(model, &QAbstractItemModel::destroyed,
302 selectionModel, &QItemSelectionModel::deleteLater);
303 }
304 if (selectionModel) {
305 QObject::disconnect(selectionModel, &QItemSelectionModel::selectionChanged,
306 q, &QAbstractItemView::selectionChanged);
307 QObject::disconnect(selectionModel, &QItemSelectionModel::currentChanged,
308 q, &QAbstractItemView::currentChanged);
309 }
310 for (const auto &info : std::as_const(indexEditorHash)) {
311 if (!info.isStatic && info.widget)
312 QObject::disconnect(info.widget, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
313 }
314#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
315 QObject::disconnect(scollerConnection);
316#endif
317}
318
319/*!
320 \class QAbstractItemView
321
322 \brief The QAbstractItemView class provides the basic functionality for
323 item view classes.
324
325 \ingroup model-view
326 \inmodule QtWidgets
327
328 QAbstractItemView class is the base class for every standard view
329 that uses a QAbstractItemModel. QAbstractItemView is an abstract
330 class and cannot itself be instantiated. It provides a standard
331 interface for interoperating with models through the signals and
332 slots mechanism, enabling subclasses to be kept up-to-date with
333 changes to their models. This class provides standard support for
334 keyboard and mouse navigation, viewport scrolling, item editing,
335 and selections. The keyboard navigation implements this
336 functionality:
337
338 \table
339 \header
340 \li Keys
341 \li Functionality
342 \row
343 \li Arrow keys
344 \li Changes the current item and selects it.
345 \row
346 \li Ctrl+Arrow keys
347 \li Changes the current item but does not select it.
348 \row
349 \li Shift+Arrow keys
350 \li Changes the current item and selects it. The previously
351 selected item(s) is not deselected.
352 \row
353 \li Ctrl+Space
354 \li Toggles selection of the current item.
355 \row
356 \li Tab/Backtab
357 \li Changes the current item to the next/previous item.
358 \row
359 \li Home/End
360 \li Selects the first/last item in the model.
361 \row
362 \li Page up/Page down
363 \li Scrolls the rows shown up/down by the number of
364 visible rows in the view.
365 \row
366 \li Ctrl+A
367 \li Selects all items in the model.
368 \endtable
369
370 Note that the above table assumes that the
371 \l{selectionMode}{selection mode} allows the operations. For
372 instance, you cannot select items if the selection mode is
373 QAbstractItemView::NoSelection.
374
375 The QAbstractItemView class is one of the \l{Model/View Classes}
376 and is part of Qt's \l{Model/View Programming}{model/view framework}.
377
378 The view classes that inherit QAbstractItemView only need
379 to implement their own view-specific functionality, such as
380 drawing items, returning the geometry of items, finding items,
381 etc.
382
383 QAbstractItemView provides common slots such as edit() and
384 setCurrentIndex(). Many protected slots are also provided, including
385 dataChanged(), rowsInserted(), rowsAboutToBeRemoved(), selectionChanged(),
386 and currentChanged().
387
388 The root item is returned by rootIndex(), and the current item by
389 currentIndex(). To make sure that an item is visible use
390 scrollTo().
391
392 Some of QAbstractItemView's functions are concerned with
393 scrolling, for example setHorizontalScrollMode() and
394 setVerticalScrollMode(). To set the range of the scroll bars, you
395 can, for example, reimplement the view's resizeEvent() function:
396
397 \snippet code/src_gui_itemviews_qabstractitemview.cpp 0
398
399 Note that the range is not updated until the widget is shown.
400
401 Several other functions are concerned with selection control; for
402 example setSelectionMode(), and setSelectionBehavior(). This class
403 provides a default selection model to work with
404 (selectionModel()), but this can be replaced by using
405 setSelectionModel() with an instance of QItemSelectionModel.
406
407 For complete control over the display and editing of items you can
408 specify a delegate with setItemDelegate().
409
410 QAbstractItemView provides a lot of protected functions. Some are
411 concerned with editing, for example, edit(), and commitData(),
412 whilst others are keyboard and mouse event handlers.
413
414 \note If you inherit QAbstractItemView and intend to update the contents
415 of the viewport, you should use viewport->update() instead of
416 \l{QWidget::update()}{update()} as all painting operations take place on the
417 viewport.
418
419 \sa {View Classes}, {Model/View Programming}, QAbstractItemModel
420*/
421
422/*!
423 \enum QAbstractItemView::SelectionMode
424
425 This enum indicates how the view responds to user selections:
426
427 \value SingleSelection When the user selects an item, any already-selected
428 item becomes unselected. It is possible for the user to deselect the selected
429 item by pressing the Ctrl key when clicking the selected item.
430
431 \value ContiguousSelection When the user selects an item in the usual way,
432 the selection is cleared and the new item selected. However, if the user
433 presses the Shift key while clicking on an item, all items between the
434 current item and the clicked item are selected or unselected, depending on
435 the state of the clicked item.
436
437 \value ExtendedSelection When the user selects an item in the usual way,
438 the selection is cleared and the new item selected. However, if the user
439 presses the Ctrl key when clicking on an item, the clicked item gets
440 toggled and all other items are left untouched. If the user presses the
441 Shift key while clicking on an item, all items between the current item
442 and the clicked item are selected or unselected, depending on the state of
443 the clicked item. Multiple items can be selected by dragging the mouse over
444 them.
445
446 \value MultiSelection When the user selects an item in the usual way, the
447 selection status of that item is toggled and the other items are left
448 alone. Multiple items can be toggled by dragging the mouse over them.
449
450 \value NoSelection Items cannot be selected.
451
452 The most commonly used modes are SingleSelection and ExtendedSelection.
453*/
454
455/*!
456 \enum QAbstractItemView::SelectionBehavior
457
458 \value SelectItems Selecting single items.
459 \value SelectRows Selecting only rows.
460 \value SelectColumns Selecting only columns.
461*/
462
463/*!
464 \enum QAbstractItemView::ScrollHint
465
466 \value EnsureVisible Scroll to ensure that the item is visible.
467 \value PositionAtTop Scroll to position the item at the top of the
468 viewport.
469 \value PositionAtBottom Scroll to position the item at the bottom of the
470 viewport.
471 \value PositionAtCenter Scroll to position the item at the center of the
472 viewport.
473*/
474
475
476/*!
477 \enum QAbstractItemView::EditTrigger
478
479 This enum describes actions which will initiate item editing.
480
481 \value NoEditTriggers No editing possible.
482 \value CurrentChanged Editing start whenever current item changes.
483 \value DoubleClicked Editing starts when an item is double clicked.
484 \value SelectedClicked Editing starts when clicking on an already selected
485 item.
486 \value EditKeyPressed Editing starts when the platform edit key has been
487 pressed over an item.
488 \value AnyKeyPressed Editing starts when any key is pressed over an item.
489 \value AllEditTriggers Editing starts for all above actions.
490*/
491
492/*!
493 \enum QAbstractItemView::CursorAction
494
495 This enum describes the different ways to navigate between items,
496 \sa moveCursor()
497
498 \value MoveUp Move to the item above the current item.
499 \value MoveDown Move to the item below the current item.
500 \value MoveLeft Move to the item left of the current item.
501 \value MoveRight Move to the item right of the current item.
502 \value MoveHome Move to the top-left corner item.
503 \value MoveEnd Move to the bottom-right corner item.
504 \value MovePageUp Move one page up above the current item.
505 \value MovePageDown Move one page down below the current item.
506 \value MoveNext Move to the item after the current item.
507 \value MovePrevious Move to the item before the current item.
508*/
509
510/*!
511 \enum QAbstractItemView::State
512
513 Describes the different states the view can be in. This is usually
514 only interesting when reimplementing your own view.
515
516 \value NoState The is the default state.
517 \value DraggingState The user is dragging items.
518 \value DragSelectingState The user is selecting items.
519 \value EditingState The user is editing an item in a widget editor.
520 \value ExpandingState The user is opening a branch of items.
521 \value CollapsingState The user is closing a branch of items.
522 \value AnimatingState The item view is performing an animation.
523*/
524
525/*!
526 \enum QAbstractItemView::ScrollMode
527
528 Describes how the scrollbar should behave. When setting the scroll mode
529 to ScrollPerPixel the single step size will adjust automatically unless
530 it was set explicitly using \l{QAbstractSlider::}{setSingleStep()}.
531 The automatic adjustment can be restored by setting the single step size to -1.
532
533 \value ScrollPerItem The view will scroll the contents one item at a time.
534 \value ScrollPerPixel The view will scroll the contents one pixel at a time.
535*/
536
537/*!
538 \fn QRect QAbstractItemView::visualRect(const QModelIndex &index) const = 0
539 Returns the rectangle on the viewport occupied by the item at \a index.
540
541 If your item is displayed in several areas then visualRect should return
542 the primary area that contains index and not the complete area that index
543 might encompasses, touch or cause drawing.
544
545 In the base class this is a pure virtual function.
546
547 \sa indexAt(), visualRegionForSelection()
548*/
549
550/*!
551 \fn void QAbstractItemView::scrollTo(const QModelIndex &index, ScrollHint hint) = 0
552
553 Scrolls the view if necessary to ensure that the item at \a index
554 is visible. The view will try to position the item according to the given \a hint.
555
556 In the base class this is a pure virtual function.
557*/
558
559/*!
560 \fn QModelIndex QAbstractItemView::indexAt(const QPoint &point) const = 0
561
562 Returns the model index of the item at the viewport coordinates \a point.
563
564 In the base class this is a pure virtual function.
565
566 \sa visualRect()
567*/
568
569/*!
570 \fn void QAbstractItemView::activated(const QModelIndex &index)
571
572 This signal is emitted when the item specified by \a index is
573 activated by the user. How to activate items depends on the
574 platform; e.g., by single- or double-clicking the item, or by
575 pressing the Return or Enter key when the item is current.
576
577 \sa clicked(), doubleClicked(), entered(), pressed()
578*/
579
580/*!
581 \fn void QAbstractItemView::entered(const QModelIndex &index)
582
583 This signal is emitted when the mouse cursor enters the item
584 specified by \a index.
585 Mouse tracking needs to be enabled for this feature to work.
586
587 \sa viewportEntered(), activated(), clicked(), doubleClicked(), pressed()
588*/
589
590/*!
591 \fn void QAbstractItemView::viewportEntered()
592
593 This signal is emitted when the mouse cursor enters the viewport.
594 Mouse tracking needs to be enabled for this feature to work.
595
596 \sa entered()
597*/
598
599/*!
600 \fn void QAbstractItemView::pressed(const QModelIndex &index)
601
602 This signal is emitted when a mouse button is pressed. The item
603 the mouse was pressed on is specified by \a index. The signal is
604 only emitted when the index is valid.
605
606 Use the QGuiApplication::mouseButtons() function to get the state
607 of the mouse buttons.
608
609 \sa activated(), clicked(), doubleClicked(), entered()
610*/
611
612/*!
613 \fn void QAbstractItemView::clicked(const QModelIndex &index)
614
615 This signal is emitted when a mouse button is left-clicked. The item
616 the mouse was clicked on is specified by \a index. The signal is
617 only emitted when the index is valid.
618
619 \sa activated(), doubleClicked(), entered(), pressed()
620*/
621
622/*!
623 \fn void QAbstractItemView::doubleClicked(const QModelIndex &index)
624
625 This signal is emitted when a mouse button is double-clicked. The
626 item the mouse was double-clicked on is specified by \a index.
627 The signal is only emitted when the index is valid.
628
629 \sa clicked(), activated()
630*/
631
632/*!
633 \fn QModelIndex QAbstractItemView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) = 0
634
635 Returns a QModelIndex object pointing to the next object in the view,
636 based on the given \a cursorAction and keyboard modifiers specified
637 by \a modifiers.
638
639 In the base class this is a pure virtual function.
640*/
641
642/*!
643 \fn int QAbstractItemView::horizontalOffset() const = 0
644
645 Returns the horizontal offset of the view.
646
647 In the base class this is a pure virtual function.
648
649 \sa verticalOffset()
650*/
651
652/*!
653 \fn int QAbstractItemView::verticalOffset() const = 0
654
655 Returns the vertical offset of the view.
656
657 In the base class this is a pure virtual function.
658
659 \sa horizontalOffset()
660*/
661
662/*!
663 \fn bool QAbstractItemView::isIndexHidden(const QModelIndex &index) const
664
665 Returns \c true if the item referred to by the given \a index is hidden in the view,
666 otherwise returns \c false.
667
668 Hiding is a view specific feature. For example in TableView a column can be marked
669 as hidden or a row in the TreeView.
670
671 In the base class this is a pure virtual function.
672*/
673
674/*!
675 \fn void QAbstractItemView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags flags)
676
677 Applies the selection \a flags to the items in or touched by the
678 rectangle, \a rect.
679
680 When implementing your own itemview setSelection should call
681 selectionModel()->select(selection, flags) where selection
682 is either an empty QModelIndex or a QItemSelection that contains
683 all items that are contained in \a rect.
684
685 \sa selectionCommand(), selectedIndexes()
686*/
687
688/*!
689 \fn QRegion QAbstractItemView::visualRegionForSelection(const QItemSelection &selection) const = 0
690
691 Returns the region from the viewport of the items in the given
692 \a selection.
693
694 In the base class this is a pure virtual function.
695
696 \sa visualRect(), selectedIndexes()
697*/
698
699/*!
700 Constructs an abstract item view with the given \a parent.
701*/
702QAbstractItemView::QAbstractItemView(QWidget *parent)
703 : QAbstractScrollArea(*(new QAbstractItemViewPrivate), parent)
704{
705 d_func()->init();
706}
707
708/*!
709 \internal
710*/
711QAbstractItemView::QAbstractItemView(QAbstractItemViewPrivate &dd, QWidget *parent)
712 : QAbstractScrollArea(dd, parent)
713{
714 d_func()->init();
715}
716
717/*!
718 Destroys the view.
719*/
720QAbstractItemView::~QAbstractItemView()
721{
722 Q_D(QAbstractItemView);
723 // stop these timers here before ~QObject
724 d->delayedReset.stop();
725 d->updateTimer.stop();
726 d->delayedEditing.stop();
727 d->delayedAutoScroll.stop();
728 d->autoScrollTimer.stop();
729 d->delayedLayout.stop();
730 d->fetchMoreTimer.stop();
731 d->disconnectAll();
732}
733
734/*!
735 Sets the \a model for the view to present.
736
737 This function will create and set a new selection model, replacing any
738 model that was previously set with setSelectionModel(). However, the old
739 selection model will not be deleted as it may be shared between several
740 views. We recommend that you delete the old selection model if it is no
741 longer required. This is done with the following code:
742
743 \snippet code/src_gui_itemviews_qabstractitemview.cpp 2
744
745 If both the old model and the old selection model do not have parents, or
746 if their parents are long-lived objects, it may be preferable to call their
747 deleteLater() functions to explicitly delete them.
748
749 The view \e{does not} take ownership of the model unless it is the model's
750 parent object because the model may be shared between many different views.
751
752 \sa selectionModel(), setSelectionModel()
753*/
754void QAbstractItemView::setModel(QAbstractItemModel *model)
755{
756 Q_D(QAbstractItemView);
757 if (model == d->model)
758 return;
759 if (d->model && d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
760 for (QMetaObject::Connection &connection : d->modelConnections)
761 disconnect(connection);
762 }
763 d->model = (model ? model : QAbstractItemModelPrivate::staticEmptyModel());
764
765 if (d->model != QAbstractItemModelPrivate::staticEmptyModel()) {
766 d->modelConnections = {
767 QObjectPrivate::connect(d->model, &QAbstractItemModel::destroyed,
768 d, &QAbstractItemViewPrivate::modelDestroyed),
769 QObject::connect(d->model, &QAbstractItemModel::dataChanged,
770 this, &QAbstractItemView::dataChanged),
771 QObjectPrivate::connect(d->model, &QAbstractItemModel::headerDataChanged,
772 d, &QAbstractItemViewPrivate::headerDataChanged),
773 QObject::connect(d->model, &QAbstractItemModel::rowsInserted,
774 this, &QAbstractItemView::rowsInserted),
775 QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsInserted,
776 d, &QAbstractItemViewPrivate::rowsInserted),
777 QObject::connect(d->model, &QAbstractItemModel::rowsAboutToBeRemoved,
778 this, &QAbstractItemView::rowsAboutToBeRemoved),
779 QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsRemoved,
780 d, &QAbstractItemViewPrivate::rowsRemoved),
781 QObjectPrivate::connect(d->model, &QAbstractItemModel::rowsMoved,
782 d, &QAbstractItemViewPrivate::rowsMoved),
783 QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsAboutToBeRemoved,
784 d, &QAbstractItemViewPrivate::columnsAboutToBeRemoved),
785 QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsRemoved,
786 d, &QAbstractItemViewPrivate::columnsRemoved),
787 QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsInserted,
788 d, &QAbstractItemViewPrivate::columnsInserted),
789 QObjectPrivate::connect(d->model, &QAbstractItemModel::columnsMoved,
790 d, &QAbstractItemViewPrivate::columnsMoved),
791 QObject::connect(d->model, &QAbstractItemModel::modelReset,
792 this, &QAbstractItemView::reset),
793 QObjectPrivate::connect(d->model, &QAbstractItemModel::layoutChanged,
794 d, &QAbstractItemViewPrivate::layoutChanged),
795 };
796 }
797
798 QItemSelectionModel *selection_model = new QItemSelectionModel(d->model, this);
799 connect(d->model, &QAbstractItemModel::destroyed,
800 selection_model, &QItemSelectionModel::deleteLater);
801 setSelectionModel(selection_model);
802
803 reset(); // kill editors, set new root and do layout
804}
805
806/*!
807 Returns the model that this view is presenting.
808*/
809QAbstractItemModel *QAbstractItemView::model() const
810{
811 Q_D(const QAbstractItemView);
812 return (d->model == QAbstractItemModelPrivate::staticEmptyModel() ? nullptr : d->model);
813}
814
815/*!
816 Sets the current selection model to the given \a selectionModel.
817
818 Note that, if you call setModel() after this function, the given \a selectionModel
819 will be replaced by one created by the view.
820
821 \note It is up to the application to delete the old selection model if it is no
822 longer needed; i.e., if it is not being used by other views. This will happen
823 automatically when its parent object is deleted. However, if it does not have a
824 parent, or if the parent is a long-lived object, it may be preferable to call its
825 deleteLater() function to explicitly delete it.
826
827 \sa selectionModel(), setModel(), clearSelection()
828*/
829void QAbstractItemView::setSelectionModel(QItemSelectionModel *selectionModel)
830{
831 // ### if the given model is null, we should use the original selection model
832 Q_ASSERT(selectionModel);
833 Q_D(QAbstractItemView);
834
835 if (Q_UNLIKELY(selectionModel->model() != d->model)) {
836 qCWarning(lcAIV, "QAbstractItemView::setSelectionModel() failed: "
837 "Trying to set a selection model, which works on "
838 "a different model than the view.");
839 return;
840 }
841
842 QItemSelection oldSelection;
843 QModelIndex oldCurrentIndex;
844
845 if (d->selectionModel) {
846 if (d->selectionModel->model() == selectionModel->model()) {
847 oldSelection = d->selectionModel->selection();
848 oldCurrentIndex = d->selectionModel->currentIndex();
849 }
850 disconnect(d->selectionModel, &QItemSelectionModel::selectionChanged,
851 this, &QAbstractItemView::selectionChanged);
852 disconnect(d->selectionModel, &QItemSelectionModel::currentChanged,
853 this, &QAbstractItemView::currentChanged);
854 }
855
856 d->selectionModel = selectionModel;
857
858 if (d->selectionModel) {
859 connect(d->selectionModel, &QItemSelectionModel::selectionChanged,
860 this, &QAbstractItemView::selectionChanged);
861 connect(d->selectionModel, &QItemSelectionModel::currentChanged,
862 this, &QAbstractItemView::currentChanged);
863
864 selectionChanged(d->selectionModel->selection(), oldSelection);
865 currentChanged(d->selectionModel->currentIndex(), oldCurrentIndex);
866 }
867}
868
869/*!
870 Returns the current selection model.
871
872 The view creates its selection model when you call setModel(), so this
873 function returns \nullptr until a model has been set. Each call to
874 setModel() with a different model replaces the selection model with a
875 new one. Connect to the selection model's signals after calling
876 setModel(), and reconnect whenever you set a different model.
877
878 \sa setSelectionModel(), selectedIndexes()
879*/
880QItemSelectionModel* QAbstractItemView::selectionModel() const
881{
882 Q_D(const QAbstractItemView);
883 return d->selectionModel;
884}
885
886/*!
887 Sets the item delegate for this view and its model to \a delegate.
888 This is useful if you want complete control over the editing and
889 display of items.
890
891 Any existing delegate will be removed, but not deleted. QAbstractItemView
892 does not take ownership of \a delegate.
893
894 \warning You should not share the same instance of a delegate between views.
895 Doing so can cause incorrect or unintuitive editing behavior since each
896 view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
897 signal, and attempt to access, modify or close an editor that has already been closed.
898
899 \sa itemDelegate()
900*/
901void QAbstractItemView::setItemDelegate(QAbstractItemDelegate *delegate)
902{
903 Q_D(QAbstractItemView);
904 if (delegate == d->itemDelegate)
905 return;
906
907 if (d->itemDelegate) {
908 if (d->delegateRefCount(d->itemDelegate) == 1)
909 d->disconnectDelegate(d->itemDelegate);
910 }
911
912 if (delegate) {
913 if (d->delegateRefCount(delegate) == 0)
914 d->connectDelegate(delegate);
915 }
916 d->itemDelegate = delegate;
917 viewport()->update();
918 d->doDelayedItemsLayout();
919}
920
921/*!
922 Returns the item delegate used by this view and model. This is
923 either one set with setItemDelegate(), or the default one.
924
925 \sa setItemDelegate()
926*/
927QAbstractItemDelegate *QAbstractItemView::itemDelegate() const
928{
929 return d_func()->itemDelegate;
930}
931
932/*!
933 \reimp
934*/
935QVariant QAbstractItemView::inputMethodQuery(Qt::InputMethodQuery query) const
936{
937 Q_D(const QAbstractItemView);
938 const QModelIndex current = currentIndex();
939 QVariant result;
940 if (current.isValid()) {
941 if (QWidget *currentEditor;
942 d->waitForIMCommit && (currentEditor = d->editorForIndex(current).widget)) {
943 // An editor is open but the initial preedit is still ongoing. Delegate
944 // queries to the editor and map coordinates from editor to this view.
945 result = currentEditor->inputMethodQuery(query);
946 if (result.typeId() == QMetaType::QRect) {
947 const QRect editorRect = result.value<QRect>();
948 result = QRect(currentEditor->mapTo(this, editorRect.topLeft()), editorRect.size());
949 }
950 } else if (query == Qt::ImCursorRectangle) {
951 const QRect visRect = visualRect(current);
952 result = QRect(d->viewport->mapTo(this, visRect.topLeft()), visRect.size());
953 }
954 }
955 if (!result.isValid())
956 result = QAbstractScrollArea::inputMethodQuery(query);
957 return result;
958}
959
960/*!
961 Sets the given item \a delegate used by this view and model for the given
962 \a row. All items on \a row will be drawn and managed by \a delegate
963 instead of using the default delegate (i.e., itemDelegate()).
964
965 Any existing row delegate for \a row will be removed, but not
966 deleted. QAbstractItemView does not take ownership of \a delegate.
967
968 \note If a delegate has been assigned to both a row and a column, the row
969 delegate (i.e., this delegate) will take precedence and manage the
970 intersecting cell index.
971
972 \warning You should not share the same instance of a delegate between views.
973 Doing so can cause incorrect or unintuitive editing behavior since each
974 view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
975 signal, and attempt to access, modify or close an editor that has already been closed.
976
977 \sa itemDelegateForRow(), setItemDelegateForColumn(), itemDelegate()
978*/
979void QAbstractItemView::setItemDelegateForRow(int row, QAbstractItemDelegate *delegate)
980{
981 Q_D(QAbstractItemView);
982 if (QAbstractItemDelegate *rowDelegate = d->rowDelegates.value(row, nullptr)) {
983 if (d->delegateRefCount(rowDelegate) == 1)
984 d->disconnectDelegate(rowDelegate);
985 d->rowDelegates.remove(row);
986 }
987 if (delegate) {
988 if (d->delegateRefCount(delegate) == 0)
989 d->connectDelegate(delegate);
990 d->rowDelegates.insert(row, delegate);
991 }
992 viewport()->update();
993 d->doDelayedItemsLayout();
994}
995
996/*!
997 Returns the item delegate used by this view and model for the given \a row,
998 or \nullptr if no delegate has been assigned. You can call itemDelegate()
999 to get a pointer to the current delegate for a given index.
1000
1001 \sa setItemDelegateForRow(), itemDelegateForColumn(), setItemDelegate()
1002*/
1003QAbstractItemDelegate *QAbstractItemView::itemDelegateForRow(int row) const
1004{
1005 Q_D(const QAbstractItemView);
1006 return d->rowDelegates.value(row, nullptr);
1007}
1008
1009/*!
1010 Sets the given item \a delegate used by this view and model for the given
1011 \a column. All items on \a column will be drawn and managed by \a delegate
1012 instead of using the default delegate (i.e., itemDelegate()).
1013
1014 Any existing column delegate for \a column will be removed, but not
1015 deleted. QAbstractItemView does not take ownership of \a delegate.
1016
1017 \note If a delegate has been assigned to both a row and a column, the row
1018 delegate will take precedence and manage the intersecting cell index.
1019
1020 \warning You should not share the same instance of a delegate between views.
1021 Doing so can cause incorrect or unintuitive editing behavior since each
1022 view connected to a given delegate may receive the \l{QAbstractItemDelegate::}{closeEditor()}
1023 signal, and attempt to access, modify or close an editor that has already been closed.
1024
1025 \sa itemDelegateForColumn(), setItemDelegateForRow(), itemDelegate()
1026*/
1027void QAbstractItemView::setItemDelegateForColumn(int column, QAbstractItemDelegate *delegate)
1028{
1029 Q_D(QAbstractItemView);
1030 if (QAbstractItemDelegate *columnDelegate = d->columnDelegates.value(column, nullptr)) {
1031 if (d->delegateRefCount(columnDelegate) == 1)
1032 d->disconnectDelegate(columnDelegate);
1033 d->columnDelegates.remove(column);
1034 }
1035 if (delegate) {
1036 if (d->delegateRefCount(delegate) == 0)
1037 d->connectDelegate(delegate);
1038 d->columnDelegates.insert(column, delegate);
1039 }
1040 viewport()->update();
1041 d->doDelayedItemsLayout();
1042}
1043
1044/*!
1045 Returns the item delegate used by this view and model for the given \a
1046 column. You can call itemDelegate() to get a pointer to the current delegate
1047 for a given index.
1048
1049 \sa setItemDelegateForColumn(), itemDelegateForRow(), itemDelegate()
1050*/
1051QAbstractItemDelegate *QAbstractItemView::itemDelegateForColumn(int column) const
1052{
1053 Q_D(const QAbstractItemView);
1054 return d->columnDelegates.value(column, nullptr);
1055}
1056
1057/*!
1058 \fn QAbstractItemDelegate *QAbstractItemView::itemDelegate(const QModelIndex &index) const
1059 \deprecated Use itemDelegateForIndex() instead.
1060
1061 Returns the item delegate used by this view and model for
1062 the given \a index.
1063*/
1064
1065/*!
1066 \since 6.0
1067
1068 Returns the item delegate used by this view and model for
1069 the given \a index.
1070
1071 \sa setItemDelegate(), setItemDelegateForRow(), setItemDelegateForColumn()
1072*/
1073QAbstractItemDelegate *QAbstractItemView::itemDelegateForIndex(const QModelIndex &index) const
1074{
1075 Q_D(const QAbstractItemView);
1076 return d->delegateForIndex(index);
1077}
1078
1079/*!
1080 \property QAbstractItemView::selectionMode
1081 \brief which selection mode the view operates in
1082
1083 This property controls whether the user can select one or many items
1084 and, in many-item selections, whether the selection must be a
1085 continuous range of items.
1086
1087 \sa SelectionMode, SelectionBehavior
1088*/
1089void QAbstractItemView::setSelectionMode(SelectionMode mode)
1090{
1091 Q_D(QAbstractItemView);
1092 d->selectionMode = mode;
1093}
1094
1095QAbstractItemView::SelectionMode QAbstractItemView::selectionMode() const
1096{
1097 Q_D(const QAbstractItemView);
1098 return d->selectionMode;
1099}
1100
1101/*!
1102 \property QAbstractItemView::selectionBehavior
1103 \brief which selection behavior the view uses
1104
1105 This property holds whether selections are done
1106 in terms of single items, rows or columns.
1107
1108 \sa SelectionMode, SelectionBehavior
1109*/
1110
1111void QAbstractItemView::setSelectionBehavior(QAbstractItemView::SelectionBehavior behavior)
1112{
1113 Q_D(QAbstractItemView);
1114 d->selectionBehavior = behavior;
1115}
1116
1117QAbstractItemView::SelectionBehavior QAbstractItemView::selectionBehavior() const
1118{
1119 Q_D(const QAbstractItemView);
1120 return d->selectionBehavior;
1121}
1122
1123/*!
1124 Sets the current item to be the item at \a index.
1125
1126 Unless the current selection mode is
1127 \l{QAbstractItemView::}{NoSelection}, the item is also selected.
1128 Note that this function also updates the starting position for any
1129 new selections the user performs.
1130
1131 To set an item as the current item without selecting it, call
1132
1133 \c{selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);}
1134
1135 \sa currentIndex(), currentChanged(), selectionMode
1136*/
1137void QAbstractItemView::setCurrentIndex(const QModelIndex &index)
1138{
1139 Q_D(QAbstractItemView);
1140 if (d->selectionModel && (!index.isValid() || d->isIndexEnabled(index))) {
1141 QItemSelectionModel::SelectionFlags command = selectionCommand(index, nullptr);
1142 d->selectionModel->setCurrentIndex(index, command);
1143 d->currentIndexSet = true;
1144 }
1145}
1146
1147/*!
1148 Returns the model index of the current item.
1149
1150 \sa setCurrentIndex()
1151*/
1152QModelIndex QAbstractItemView::currentIndex() const
1153{
1154 Q_D(const QAbstractItemView);
1155 return d->selectionModel ? d->selectionModel->currentIndex() : QModelIndex();
1156}
1157
1158
1159/*!
1160 Reset the internal state of the view.
1161
1162 \warning This function will reset open editors, scroll bar positions,
1163 selections, etc. Existing changes will not be committed. If you would like
1164 to save your changes when resetting the view, you can reimplement this
1165 function, commit your changes, and then call the superclass'
1166 implementation.
1167*/
1168void QAbstractItemView::reset()
1169{
1170 Q_D(QAbstractItemView);
1171 d->delayedReset.stop(); //make sure we stop the timer
1172 // Taking a copy because releaseEditor() eventurally calls deleteLater() on the
1173 // editor, which calls QCoreApplication::postEvent(), the latter may invoke unknown
1174 // code that may modify d->indexEditorHash.
1175 const auto copy = d->indexEditorHash;
1176 for (const auto &[index, info] : copy.asKeyValueRange()) {
1177 if (info.widget)
1178 d->releaseEditor(info.widget.data(), d->indexForEditor(info.widget.data()));
1179 }
1180 d->editorIndexHash.clear();
1181 d->indexEditorHash.clear();
1182 d->persistent.clear();
1183 d->currentIndexSet = false;
1184 setState(NoState);
1185 setRootIndex(QModelIndex());
1186 if (d->selectionModel)
1187 d->selectionModel->reset();
1188#if QT_CONFIG(accessibility)
1189 if (QAccessible::isActive()) {
1190 QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::ModelReset);
1191 QAccessible::updateAccessibility(&accessibleEvent);
1192 }
1193#endif
1194 d->updateGeometry();
1195}
1196
1197/*!
1198 Sets the root item to the item at the given \a index.
1199
1200 \sa rootIndex()
1201*/
1202void QAbstractItemView::setRootIndex(const QModelIndex &index)
1203{
1204 Q_D(QAbstractItemView);
1205 if (Q_UNLIKELY(index.isValid() && index.model() != d->model)) {
1206 qWarning("QAbstractItemView::setRootIndex failed : index must be from the currently set model");
1207 return;
1208 }
1209 d->root = index;
1210#if QT_CONFIG(accessibility)
1211 if (QAccessible::isActive()) {
1212 QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::ModelReset);
1213 QAccessible::updateAccessibility(&accessibleEvent);
1214 }
1215#endif
1216 d->doDelayedItemsLayout();
1217 d->updateGeometry();
1218}
1219
1220/*!
1221 Returns the model index of the model's root item. The root item is
1222 the parent item to the view's toplevel items. The root can be invalid.
1223
1224 \sa setRootIndex()
1225*/
1226QModelIndex QAbstractItemView::rootIndex() const
1227{
1228 return QModelIndex(d_func()->root);
1229}
1230
1231/*!
1232 Selects all items in the view.
1233 This function will use the selection behavior
1234 set on the view when selecting.
1235
1236 \sa setSelection(), selectedIndexes(), clearSelection()
1237*/
1238void QAbstractItemView::selectAll()
1239{
1240 Q_D(QAbstractItemView);
1241 const SelectionMode mode = d->selectionMode;
1242 switch (mode) {
1243 case MultiSelection:
1244 case ExtendedSelection:
1245 d->selectAll(QItemSelectionModel::ClearAndSelect
1246 | d->selectionBehaviorFlags());
1247 break;
1248 case NoSelection:
1249 case ContiguousSelection:
1250 if (d->model->hasChildren(d->root))
1251 d->selectAll(selectionCommand(d->model->index(0, 0, d->root)));
1252 break;
1253 case SingleSelection:
1254 break;
1255 }
1256}
1257
1258/*!
1259 Starts editing the item corresponding to the given \a index if it is
1260 editable.
1261
1262 Note that this function does not change the current index. Since the current
1263 index defines the next and previous items to edit, users may find that
1264 keyboard navigation does not work as expected. To provide consistent navigation
1265 behavior, call setCurrentIndex() before this function with the same model
1266 index.
1267
1268 \sa QModelIndex::flags()
1269*/
1270void QAbstractItemView::edit(const QModelIndex &index)
1271{
1272 Q_D(QAbstractItemView);
1273 if (Q_UNLIKELY(!d->isIndexValid(index)))
1274 qCWarning(lcAIV, "edit: index was invalid");
1275 if (Q_UNLIKELY(!edit(index, AllEditTriggers, nullptr)))
1276 qCWarning(lcAIV, "edit: editing failed");
1277}
1278
1279/*!
1280 Deselects all selected items. The current index will not be changed.
1281
1282 \sa setSelection(), selectAll()
1283*/
1284void QAbstractItemView::clearSelection()
1285{
1286 Q_D(QAbstractItemView);
1287 if (d->selectionModel)
1288 d->selectionModel->clearSelection();
1289}
1290
1291/*!
1292 \internal
1293
1294 This function is intended to lay out the items in the view.
1295 The default implementation just calls updateGeometries() and updates the viewport.
1296*/
1297void QAbstractItemView::doItemsLayout()
1298{
1299 Q_D(QAbstractItemView);
1300 d->interruptDelayedItemsLayout();
1301 updateGeometries();
1302 d->viewport->update();
1303}
1304
1305/*!
1306 \property QAbstractItemView::editTriggers
1307 \brief which actions will initiate item editing
1308
1309 This property is a selection of flags defined by
1310 \l{EditTrigger}, combined using the OR
1311 operator. The view will only initiate the editing of an item if the
1312 action performed is set in this property.
1313
1314 The default value is:
1315 \list
1316 \li for QTableView: DoubleClicked|AnyKeyPressed
1317 \li for all other views: DoubleClicked|EditKeyPressed
1318 \endlist
1319*/
1320void QAbstractItemView::setEditTriggers(EditTriggers actions)
1321{
1322 Q_D(QAbstractItemView);
1323 d->editTriggers = actions;
1324}
1325
1326QAbstractItemView::EditTriggers QAbstractItemView::editTriggers() const
1327{
1328 Q_D(const QAbstractItemView);
1329 return d->editTriggers;
1330}
1331
1332/*!
1333 \property QAbstractItemView::verticalScrollMode
1334 \brief how the view scrolls its contents in the vertical direction
1335
1336 This property controls how the view scroll its contents vertically.
1337 Scrolling can be done either per pixel or per item. Its default value
1338 comes from the style via the QStyle::SH_ItemView_ScrollMode style hint.
1339*/
1340
1341void QAbstractItemView::setVerticalScrollMode(ScrollMode mode)
1342{
1343 Q_D(QAbstractItemView);
1344 d->verticalScrollModeSet = true;
1345 if (mode == d->verticalScrollMode)
1346 return;
1347 QModelIndex topLeft = indexAt(QPoint(0, 0));
1348 d->verticalScrollMode = mode;
1349 if (mode == ScrollPerItem)
1350 verticalScrollBar()->d_func()->itemviewChangeSingleStep(1); // setSingleStep(-1) => step with 1
1351 else
1352 verticalScrollBar()->setSingleStep(-1); // Ensure that the view can update single step
1353 updateGeometries(); // update the scroll bars
1354 scrollTo(topLeft, QAbstractItemView::PositionAtTop);
1355}
1356
1357QAbstractItemView::ScrollMode QAbstractItemView::verticalScrollMode() const
1358{
1359 Q_D(const QAbstractItemView);
1360 return d->verticalScrollMode;
1361}
1362
1363void QAbstractItemView::resetVerticalScrollMode()
1364{
1365 auto sm = static_cast<ScrollMode>(style()->styleHint(QStyle::SH_ItemView_ScrollMode, nullptr, this, nullptr));
1366 setVerticalScrollMode(sm);
1367 d_func()->verticalScrollModeSet = false;
1368}
1369
1370/*!
1371 \property QAbstractItemView::horizontalScrollMode
1372 \brief how the view scrolls its contents in the horizontal direction
1373
1374 This property controls how the view scroll its contents horizontally.
1375 Scrolling can be done either per pixel or per item. Its default value
1376 comes from the style via the QStyle::SH_ItemView_ScrollMode style hint.
1377*/
1378
1379void QAbstractItemView::setHorizontalScrollMode(ScrollMode mode)
1380{
1381 Q_D(QAbstractItemView);
1382 d->horizontalScrollModeSet = true;
1383 if (mode == d->horizontalScrollMode)
1384 return;
1385 d->horizontalScrollMode = mode;
1386 if (mode == ScrollPerItem)
1387 horizontalScrollBar()->d_func()->itemviewChangeSingleStep(1); // setSingleStep(-1) => step with 1
1388 else
1389 horizontalScrollBar()->setSingleStep(-1); // Ensure that the view can update single step
1390 updateGeometries(); // update the scroll bars
1391}
1392
1393QAbstractItemView::ScrollMode QAbstractItemView::horizontalScrollMode() const
1394{
1395 Q_D(const QAbstractItemView);
1396 return d->horizontalScrollMode;
1397}
1398
1399void QAbstractItemView::resetHorizontalScrollMode()
1400{
1401 auto sm = static_cast<ScrollMode>(style()->styleHint(QStyle::SH_ItemView_ScrollMode, nullptr, this, nullptr));
1402 setHorizontalScrollMode(sm);
1403 d_func()->horizontalScrollModeSet = false;
1404}
1405
1406#if QT_CONFIG(draganddrop)
1407/*!
1408 \property QAbstractItemView::dragDropOverwriteMode
1409 \brief the view's drag and drop behavior
1410
1411 If its value is \c true, the selected data will overwrite the
1412 existing item data when dropped, while moving the data will clear
1413 the item. If its value is \c false, the selected data will be
1414 inserted as a new item when the data is dropped. When the data is
1415 moved, the item is removed as well.
1416
1417 The default value is \c false, as in the QListView and QTreeView
1418 subclasses. In the QTableView subclass, on the other hand, the
1419 property has been set to \c true.
1420
1421 Note: This is not intended to prevent overwriting of items.
1422 The model's implementation of flags() should do that by not
1423 returning Qt::ItemIsDropEnabled.
1424
1425 \sa dragDropMode
1426*/
1427void QAbstractItemView::setDragDropOverwriteMode(bool overwrite)
1428{
1429 Q_D(QAbstractItemView);
1430 d->overwrite = overwrite;
1431}
1432
1433bool QAbstractItemView::dragDropOverwriteMode() const
1434{
1435 Q_D(const QAbstractItemView);
1436 return d->overwrite;
1437}
1438#endif
1439
1440/*!
1441 \property QAbstractItemView::autoScroll
1442 \brief whether autoscrolling in drag move events is enabled
1443
1444 If this property is set to true (the default), the
1445 QAbstractItemView automatically scrolls the contents of the view
1446 if the user drags within 16 pixels of the viewport edge. If the current
1447 item changes, then the view will scroll automatically to ensure that the
1448 current item is fully visible.
1449
1450 This property only works if the viewport accepts drops. Autoscroll is
1451 switched off by setting this property to false.
1452*/
1453
1454void QAbstractItemView::setAutoScroll(bool enable)
1455{
1456 Q_D(QAbstractItemView);
1457 d->autoScroll = enable;
1458}
1459
1460bool QAbstractItemView::hasAutoScroll() const
1461{
1462 Q_D(const QAbstractItemView);
1463 return d->autoScroll;
1464}
1465
1466/*!
1467 \property QAbstractItemView::autoScrollMargin
1468 \brief the size of the area when auto scrolling is triggered
1469
1470 This property controls the size of the area at the edge of the viewport that
1471 triggers autoscrolling. The default value is 16 pixels.
1472*/
1473void QAbstractItemView::setAutoScrollMargin(int margin)
1474{
1475 Q_D(QAbstractItemView);
1476 d->autoScrollMargin = margin;
1477}
1478
1479int QAbstractItemView::autoScrollMargin() const
1480{
1481 Q_D(const QAbstractItemView);
1482 return d->autoScrollMargin;
1483}
1484
1485/*!
1486 \property QAbstractItemView::tabKeyNavigation
1487 \brief whether item navigation with tab and backtab is enabled.
1488*/
1489
1490void QAbstractItemView::setTabKeyNavigation(bool enable)
1491{
1492 Q_D(QAbstractItemView);
1493 d->tabKeyNavigation = enable;
1494}
1495
1496bool QAbstractItemView::tabKeyNavigation() const
1497{
1498 Q_D(const QAbstractItemView);
1499 return d->tabKeyNavigation;
1500}
1501
1502/*!
1503 \since 5.2
1504 \reimp
1505*/
1506QSize QAbstractItemView::viewportSizeHint() const
1507{
1508 return QAbstractScrollArea::viewportSizeHint();
1509}
1510
1511#if QT_CONFIG(draganddrop)
1512/*!
1513 \property QAbstractItemView::showDropIndicator
1514 \brief whether the drop indicator is shown when dragging items and dropping.
1515
1516 \sa dragEnabled, DragDropMode, dragDropOverwriteMode, acceptDrops
1517*/
1518
1519void QAbstractItemView::setDropIndicatorShown(bool enable)
1520{
1521 Q_D(QAbstractItemView);
1522 d->showDropIndicator = enable;
1523}
1524
1525bool QAbstractItemView::showDropIndicator() const
1526{
1527 Q_D(const QAbstractItemView);
1528 return d->showDropIndicator;
1529}
1530
1531/*!
1532 \property QAbstractItemView::dragEnabled
1533 \brief whether the view supports dragging of its own items
1534
1535 \sa showDropIndicator, DragDropMode, dragDropOverwriteMode, acceptDrops
1536*/
1537
1538void QAbstractItemView::setDragEnabled(bool enable)
1539{
1540 Q_D(QAbstractItemView);
1541 d->dragEnabled = enable;
1542}
1543
1544bool QAbstractItemView::dragEnabled() const
1545{
1546 Q_D(const QAbstractItemView);
1547 return d->dragEnabled;
1548}
1549
1550/*!
1551 \enum QAbstractItemView::DragDropMode
1552
1553 Describes the various drag and drop events the view can act upon.
1554 By default the view does not support dragging or dropping (\c
1555 NoDragDrop).
1556
1557 \value NoDragDrop Does not support dragging or dropping.
1558 \value DragOnly The view supports dragging of its own items
1559 \value DropOnly The view accepts drops
1560 \value DragDrop The view supports both dragging and dropping
1561 \value InternalMove The view accepts move (\b{not copy}) operations only
1562 from itself.
1563
1564 Note that the model used needs to provide support for drag and drop operations.
1565
1566 \sa setDragDropMode(), {Using drag and drop with item views}
1567*/
1568
1569/*!
1570 \property QAbstractItemView::dragDropMode
1571 \brief the drag and drop event the view will act upon
1572
1573 \sa showDropIndicator, dragDropOverwriteMode
1574*/
1575void QAbstractItemView::setDragDropMode(DragDropMode behavior)
1576{
1577 Q_D(QAbstractItemView);
1578 d->dragDropMode = behavior;
1579 setDragEnabled(behavior == DragOnly || behavior == DragDrop || behavior == InternalMove);
1580 setAcceptDrops(behavior == DropOnly || behavior == DragDrop || behavior == InternalMove);
1581}
1582
1583QAbstractItemView::DragDropMode QAbstractItemView::dragDropMode() const
1584{
1585 Q_D(const QAbstractItemView);
1586 DragDropMode setBehavior = d->dragDropMode;
1587 if (!dragEnabled() && !acceptDrops())
1588 return NoDragDrop;
1589
1590 if (dragEnabled() && !acceptDrops())
1591 return DragOnly;
1592
1593 if (!dragEnabled() && acceptDrops())
1594 return DropOnly;
1595
1596 if (dragEnabled() && acceptDrops()) {
1597 if (setBehavior == InternalMove)
1598 return setBehavior;
1599 else
1600 return DragDrop;
1601 }
1602
1603 return NoDragDrop;
1604}
1605
1606/*!
1607 \property QAbstractItemView::defaultDropAction
1608 \brief the drop action that will be used by default in QAbstractItemView::drag().
1609
1610 If the property is not set, the drop action is CopyAction when the supported
1611 actions support CopyAction.
1612
1613 \sa showDropIndicator, dragDropOverwriteMode
1614*/
1615void QAbstractItemView::setDefaultDropAction(Qt::DropAction dropAction)
1616{
1617 Q_D(QAbstractItemView);
1618 d->defaultDropAction = dropAction;
1619}
1620
1621Qt::DropAction QAbstractItemView::defaultDropAction() const
1622{
1623 Q_D(const QAbstractItemView);
1624 return d->defaultDropAction;
1625}
1626
1627#endif // QT_CONFIG(draganddrop)
1628
1629/*!
1630 \property QAbstractItemView::alternatingRowColors
1631 \brief whether to draw the background using alternating colors
1632
1633 If this property is \c true, the item background will be drawn using
1634 QPalette::Base and QPalette::AlternateBase; otherwise the background
1635 will be drawn using the QPalette::Base color.
1636
1637 By default, this property is \c false.
1638*/
1639void QAbstractItemView::setAlternatingRowColors(bool enable)
1640{
1641 Q_D(QAbstractItemView);
1642 d->alternatingColors = enable;
1643 if (isVisible())
1644 d->viewport->update();
1645}
1646
1647bool QAbstractItemView::alternatingRowColors() const
1648{
1649 Q_D(const QAbstractItemView);
1650 return d->alternatingColors;
1651}
1652
1653/*!
1654 \property QAbstractItemView::iconSize
1655 \brief the size of items' icons
1656
1657 Setting this property when the view is visible will cause the
1658 items to be laid out again.
1659*/
1660void QAbstractItemView::setIconSize(const QSize &size)
1661{
1662 Q_D(QAbstractItemView);
1663 if (size == d->iconSize)
1664 return;
1665 d->iconSize = size;
1666 d->doDelayedItemsLayout();
1667 emit iconSizeChanged(size);
1668}
1669
1670QSize QAbstractItemView::iconSize() const
1671{
1672 Q_D(const QAbstractItemView);
1673 return d->iconSize;
1674}
1675
1676/*!
1677 \property QAbstractItemView::textElideMode
1678
1679 \brief the position of the "..." in elided text.
1680
1681 The default value for all item views is Qt::ElideRight.
1682*/
1683void QAbstractItemView::setTextElideMode(Qt::TextElideMode mode)
1684{
1685 Q_D(QAbstractItemView);
1686 d->textElideMode = mode;
1687}
1688
1689Qt::TextElideMode QAbstractItemView::textElideMode() const
1690{
1691 return d_func()->textElideMode;
1692}
1693
1694/*!
1695 \reimp
1696*/
1697bool QAbstractItemView::focusNextPrevChild(bool next)
1698{
1699 Q_D(QAbstractItemView);
1700 if (d->tabKeyNavigation && isVisible() && isEnabled() && d->viewport->isEnabled()) {
1701 QKeyEvent event(QEvent::KeyPress, next ? Qt::Key_Tab : Qt::Key_Backtab, Qt::NoModifier);
1702 keyPressEvent(&event);
1703 if (event.isAccepted())
1704 return true;
1705 }
1706 return QAbstractScrollArea::focusNextPrevChild(next);
1707}
1708
1709/*!
1710 \reimp
1711*/
1712bool QAbstractItemView::event(QEvent *event)
1713{
1714 Q_D(QAbstractItemView);
1715 switch (event->type()) {
1716 case QEvent::Paint:
1717 //we call this here because the scrollbars' visibility might be altered
1718 //so this can't be done in the paintEvent method
1719 d->executePostedLayout(); //make sure we set the layout properly
1720 break;
1721 case QEvent::Show:
1722 d->executePostedLayout(); //make sure we set the layout properly
1723 if (d->shouldScrollToCurrentOnShow) {
1724 d->shouldScrollToCurrentOnShow = false;
1725 const QModelIndex current = currentIndex();
1726 if (current.isValid() && (d->state == QAbstractItemView::EditingState || d->autoScroll))
1727 scrollTo(current);
1728 }
1729 break;
1730 case QEvent::LocaleChange:
1731 viewport()->update();
1732 break;
1733 case QEvent::LayoutDirectionChange:
1734 case QEvent::ApplicationLayoutDirectionChange:
1735 updateGeometries();
1736 break;
1737 case QEvent::StyleChange:
1738 doItemsLayout();
1739 if (!d->verticalScrollModeSet)
1740 resetVerticalScrollMode();
1741 if (!d->horizontalScrollModeSet)
1742 resetHorizontalScrollMode();
1743 break;
1744 case QEvent::FocusOut:
1745 d->checkPersistentEditorFocus();
1746 break;
1747 case QEvent::FontChange:
1748 d->doDelayedItemsLayout(); // the size of the items will change
1749 break;
1750 default:
1751 break;
1752 }
1753 return QAbstractScrollArea::event(event);
1754}
1755
1756/*!
1757 \fn bool QAbstractItemView::viewportEvent(QEvent *event)
1758
1759 This function is used to handle tool tips, and What's
1760 This? mode, if the given \a event is a QEvent::ToolTip,or a
1761 QEvent::WhatsThis. It passes all other
1762 events on to its base class viewportEvent() handler.
1763
1764 Returns \c true if \a event has been recognized and processed; otherwise,
1765 returns \c false.
1766*/
1767bool QAbstractItemView::viewportEvent(QEvent *event)
1768{
1769 Q_D(QAbstractItemView);
1770 switch (event->type()) {
1771 case QEvent::Paint:
1772 // Similar to pre-painting in QAbstractItemView::event to update scrollbar
1773 // visibility, make sure that all pending layout requests have been executed
1774 // so that the view's data structures are up-to-date before rendering.
1775 d->executePostedLayout();
1776 break;
1777 case QEvent::HoverMove:
1778 case QEvent::HoverEnter:
1779 d->setHoverIndex(indexAt(static_cast<QHoverEvent*>(event)->position().toPoint()));
1780 break;
1781 case QEvent::HoverLeave:
1782 d->setHoverIndex(QModelIndex());
1783 break;
1784 case QEvent::Enter:
1785 d->viewportEnteredNeeded = true;
1786 break;
1787 case QEvent::Leave:
1788 d->setHoverIndex(QModelIndex()); // If we've left, no hover should be needed anymore
1789 #if QT_CONFIG(statustip)
1790 if (d->shouldClearStatusTip && d->parent) {
1791 QString empty;
1792 QStatusTipEvent tip(empty);
1793 QCoreApplication::sendEvent(d->parent, &tip);
1794 d->shouldClearStatusTip = false;
1795 }
1796 #endif
1797 d->enteredIndex = QModelIndex();
1798 break;
1799 case QEvent::ToolTip:
1800 case QEvent::QueryWhatsThis:
1801 case QEvent::WhatsThis: {
1802 QHelpEvent *he = static_cast<QHelpEvent*>(event);
1803 const QModelIndex index = indexAt(he->pos());
1804 QStyleOptionViewItem option;
1805 initViewItemOption(&option);
1806 option.rect = visualRect(index);
1807 option.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
1808
1809 QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
1810 if (!delegate)
1811 return false;
1812 return delegate->helpEvent(he, this, option, index);
1813 }
1814 case QEvent::FontChange:
1815 d->doDelayedItemsLayout(); // the size of the items will change
1816 break;
1817 case QEvent::WindowActivate:
1818 case QEvent::WindowDeactivate:
1819 d->viewport->update();
1820 break;
1821 case QEvent::ScrollPrepare:
1822 executeDelayedItemsLayout();
1823#if QT_CONFIG(gestures) && QT_CONFIG(scroller)
1824 d->scollerConnection = QObjectPrivate::connect(
1825 QScroller::scroller(d->viewport), &QScroller::stateChanged,
1826 d, &QAbstractItemViewPrivate::scrollerStateChanged,
1827 Qt::UniqueConnection);
1828#endif
1829 break;
1830
1831 default:
1832 break;
1833 }
1834 return QAbstractScrollArea::viewportEvent(event);
1835}
1836
1837/*!
1838 This function is called with the given \a event when a mouse button is pressed
1839 while the cursor is inside the widget. If a valid item is pressed on it is made
1840 into the current item. This function emits the pressed() signal.
1841*/
1842void QAbstractItemView::mousePressEvent(QMouseEvent *event)
1843{
1844 Q_D(QAbstractItemView);
1845 d->releaseFromDoubleClick = false;
1846 d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
1847 QPoint pos = event->position().toPoint();
1848 QPersistentModelIndex index = indexAt(pos);
1849
1850 // this is the mouse press event that closed the last editor (via focus event)
1851 d->pressClosedEditor = d->pressClosedEditorWatcher.isActive() && d->lastEditedIndex == index;
1852
1853 if (!d->selectionModel || (d->state == EditingState && d->hasEditor(index)))
1854 return;
1855
1856 d->pressedAlreadySelected = d->selectionModel->isSelected(index);
1857 d->pressedIndex = index;
1858 d->pressedModifiers = event->modifiers();
1859 QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
1860 d->noSelectionOnMousePress = command == QItemSelectionModel::NoUpdate || !index.isValid();
1861 QPoint offset = d->offset();
1862 d->draggedPosition = pos + offset;
1863
1864#if QT_CONFIG(draganddrop)
1865 // update the pressed position when drag was enable
1866 if (d->dragEnabled)
1867 d->pressedPosition = d->draggedPosition;
1868#endif
1869
1870 if (!(command & QItemSelectionModel::Current)) {
1871 d->pressedPosition = pos + offset;
1872 d->currentSelectionStartIndex = index;
1873 }
1874 else if (!d->currentSelectionStartIndex.isValid())
1875 d->currentSelectionStartIndex = currentIndex();
1876
1877 if (edit(index, NoEditTriggers, event))
1878 return;
1879
1880 if (index.isValid() && d->isIndexEnabled(index)) {
1881 // we disable scrollTo for mouse press so the item doesn't change position
1882 // when the user is interacting with it (ie. clicking on it)
1883 bool autoScroll = d->autoScroll;
1884 d->autoScroll = false;
1885 d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
1886 d->autoScroll = autoScroll;
1887 if (command.testFlag(QItemSelectionModel::Toggle)) {
1888 command &= ~QItemSelectionModel::Toggle;
1889 d->ctrlDragSelectionFlag = d->selectionModel->isSelected(index) ? QItemSelectionModel::Deselect : QItemSelectionModel::Select;
1890 command |= d->ctrlDragSelectionFlag;
1891 }
1892
1893 if (!(command & QItemSelectionModel::Current)) {
1894 setSelection(QRect(pos, QSize(1, 1)), command);
1895 } else {
1896 QRect rect(visualRect(d->currentSelectionStartIndex).center(), pos);
1897 setSelection(rect, command);
1898 }
1899
1900 // signal handlers may change the model
1901 emit pressed(index);
1902 if (d->autoScroll) {
1903 //we delay the autoscrolling to filter out double click event
1904 //100 is to be sure that there won't be a double-click misinterpreted as a 2 single clicks
1905 d->delayedAutoScroll.start(QApplication::doubleClickInterval()+100, this);
1906 }
1907
1908 } else {
1909 // Forces a finalize() even if mouse is pressed, but not on a item
1910 d->selectionModel->select(QModelIndex(), QItemSelectionModel::Select);
1911 }
1912}
1913
1914/*!
1915 This function is called with the given \a event when a mouse move event is
1916 sent to the widget. If a selection is in progress and new items are moved
1917 over the selection is extended; if a drag is in progress it is continued.
1918*/
1919void QAbstractItemView::mouseMoveEvent(QMouseEvent *event)
1920{
1921 Q_D(QAbstractItemView);
1922 QPoint bottomRight = event->position().toPoint();
1923
1924 d->draggedPosition = bottomRight + d->offset();
1925
1926 if (state() == ExpandingState || state() == CollapsingState)
1927 return;
1928
1929#if QT_CONFIG(draganddrop)
1930 if (state() == DraggingState) {
1931 d->maybeStartDrag(bottomRight);
1932 return;
1933 }
1934#endif // QT_CONFIG(draganddrop)
1935
1936 QPersistentModelIndex index = indexAt(bottomRight);
1937 QModelIndex buddy = d->model->buddy(d->pressedIndex);
1938 if ((state() == EditingState && d->hasEditor(buddy))
1939 || edit(index, NoEditTriggers, event))
1940 return;
1941
1942 const QPoint topLeft =
1943 d->selectionMode != SingleSelection ? d->pressedPosition - d->offset() : bottomRight;
1944
1945 d->checkMouseMove(index);
1946
1947#if QT_CONFIG(draganddrop)
1948 if (d->pressedIndex.isValid()
1949 && d->dragEnabled
1950 && (state() != DragSelectingState)
1951 && (event->buttons() != Qt::NoButton)
1952 && !d->selectedDraggableIndexes().isEmpty()) {
1953 setState(DraggingState);
1954 d->maybeStartDrag(bottomRight);
1955 return;
1956 }
1957#endif
1958
1959 if ((event->buttons() & Qt::LeftButton) && d->selectionAllowed(index) && d->selectionModel) {
1960 setState(DragSelectingState);
1961 QItemSelectionModel::SelectionFlags command = selectionCommand(index, event);
1962 if (d->ctrlDragSelectionFlag != QItemSelectionModel::NoUpdate && command.testFlag(QItemSelectionModel::Toggle)) {
1963 command &= ~QItemSelectionModel::Toggle;
1964 command |= d->ctrlDragSelectionFlag;
1965 }
1966
1967 // Do the normalize ourselves, since QRect::normalized() is flawed
1968 QRect selectionRect = QRect(topLeft, bottomRight);
1969 setSelection(selectionRect, command);
1970
1971 // set at the end because it might scroll the view
1972 if (index.isValid() && (index != d->selectionModel->currentIndex()) && d->isIndexEnabled(index))
1973 d->selectionModel->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
1974 else if (d->shouldAutoScroll(event->pos()) && !d->autoScrollTimer.isActive())
1975 startAutoScroll();
1976 }
1977}
1978
1979/*!
1980 This function is called with the given \a event when a mouse button is released,
1981 after a mouse press event on the widget. If a user presses the mouse inside your
1982 widget and then drags the mouse to another location before releasing the mouse button,
1983 your widget receives the release event. The function will emit the clicked() signal if an
1984 item was being pressed.
1985*/
1986void QAbstractItemView::mouseReleaseEvent(QMouseEvent *event)
1987{
1988 Q_D(QAbstractItemView);
1989 const bool releaseFromDoubleClick = d->releaseFromDoubleClick;
1990 d->releaseFromDoubleClick = false;
1991
1992 QPoint pos = event->position().toPoint();
1993 QPersistentModelIndex index = indexAt(pos);
1994
1995 if (state() == EditingState) {
1996 if (d->isIndexValid(index)
1997 && d->isIndexEnabled(index)
1998 && d->sendDelegateEvent(index, event))
1999 update(index);
2000 return;
2001 }
2002
2003 bool click = (index == d->pressedIndex && index.isValid() && !releaseFromDoubleClick);
2004 bool selectedClicked = click && d->pressedAlreadySelected
2005 && (event->button() == Qt::LeftButton)
2006 && (event->modifiers() == Qt::NoModifier);
2007 EditTrigger trigger = (selectedClicked ? SelectedClicked : NoEditTriggers);
2008 const bool edited = click && !d->pressClosedEditor ? edit(index, trigger, event) : false;
2009
2010 d->ctrlDragSelectionFlag = QItemSelectionModel::NoUpdate;
2011
2012 if (d->selectionModel && d->noSelectionOnMousePress) {
2013 d->noSelectionOnMousePress = false;
2014 if (!d->pressClosedEditor)
2015 d->selectionModel->select(index, selectionCommand(index, event));
2016 }
2017
2018 d->pressClosedEditor = false;
2019 stopAutoScroll();
2020 setState(NoState);
2021
2022 if (click) {
2023 if (event->button() == Qt::LeftButton)
2024 emit clicked(index);
2025 if (edited)
2026 return;
2027 QStyleOptionViewItem option;
2028 initViewItemOption(&option);
2029 if (d->pressedAlreadySelected)
2030 option.state |= QStyle::State_Selected;
2031 if ((d->model->flags(index) & Qt::ItemIsEnabled)
2032 && style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, &option, this))
2033 emit activated(index);
2034 }
2035}
2036
2037/*!
2038 This function is called with the given \a event when a mouse button is
2039 double clicked inside the widget. If the double-click is on a valid item it
2040 emits the doubleClicked() signal and calls edit() on the item.
2041*/
2042void QAbstractItemView::mouseDoubleClickEvent(QMouseEvent *event)
2043{
2044 Q_D(QAbstractItemView);
2045
2046 QModelIndex index = indexAt(event->position().toPoint());
2047 if (!index.isValid()
2048 || !d->isIndexEnabled(index)
2049 || (d->pressedIndex != index)) {
2050 QMouseEvent me(QEvent::MouseButtonPress,
2051 event->position(), event->scenePosition(), event->globalPosition(),
2052 event->button(), event->buttons(), event->modifiers(),
2053 event->source(), event->pointingDevice());
2054 mousePressEvent(&me);
2055 return;
2056 }
2057 // signal handlers may change the model
2058 QPersistentModelIndex persistent = index;
2059 emit doubleClicked(persistent);
2060 if ((event->button() == Qt::LeftButton) && !edit(persistent, DoubleClicked, event)
2061 && !style()->styleHint(QStyle::SH_ItemView_ActivateItemOnSingleClick, nullptr, this))
2062 emit activated(persistent);
2063 d->releaseFromDoubleClick = true;
2064}
2065
2066#if QT_CONFIG(draganddrop)
2067
2068/*!
2069 This function is called with the given \a event when a drag and drop operation enters
2070 the widget. If the drag is over a valid dropping place (e.g. over an item that
2071 accepts drops), the event is accepted; otherwise it is ignored.
2072
2073 \sa dropEvent(), startDrag()
2074*/
2075void QAbstractItemView::dragEnterEvent(QDragEnterEvent *event)
2076{
2077 if (dragDropMode() == InternalMove
2078 && (event->source() != this|| !(event->possibleActions() & Qt::MoveAction)))
2079 return;
2080
2081 if (d_func()->canDrop(event)) {
2082 event->accept();
2083 setState(DraggingState);
2084 } else {
2085 event->ignore();
2086 }
2087}
2088
2089/*!
2090 This function is called continuously with the given \a event during a drag and
2091 drop operation over the widget. It can cause the view to scroll if, for example,
2092 the user drags a selection to view's right or bottom edge. In this case, the
2093 event will be accepted; otherwise it will be ignored.
2094
2095 \sa dropEvent(), startDrag()
2096*/
2097void QAbstractItemView::dragMoveEvent(QDragMoveEvent *event)
2098{
2099 Q_D(QAbstractItemView);
2100 d->draggedPosition = event->position().toPoint() + d->offset();
2101 if (dragDropMode() == InternalMove
2102 && (event->source() != this || !(event->possibleActions() & Qt::MoveAction)))
2103 return;
2104
2105 // ignore by default
2106 event->ignore();
2107
2108 QModelIndex index = indexAt(event->position().toPoint());
2109 d->hover = index;
2110 if (!d->droppingOnItself(event, index)
2111 && d->canDrop(event)) {
2112
2113 if (index.isValid() && d->showDropIndicator) {
2114 QRect rect = visualRect(index);
2115 d->dropIndicatorPosition = d->position(event->position().toPoint(), rect, index);
2116 if (d->selectionBehavior == QAbstractItemView::SelectRows
2117 && d->dropIndicatorPosition != OnViewport
2118 && (d->dropIndicatorPosition != OnItem || event->source() == this)) {
2119 const int maxCol = d->model->columnCount(index.parent()) - 1;
2120 const auto idx = index.column() > 0 ? index.siblingAtColumn(0) : index;
2121 rect = d->intersectedRect(viewport()->rect(), idx, idx.siblingAtColumn(maxCol));
2122 }
2123 switch (d->dropIndicatorPosition) {
2124 case AboveItem:
2125 if (d->isIndexDropEnabled(index.parent())) {
2126 d->dropIndicatorRect = QRect(rect.left(), rect.top(), rect.width(), 0);
2127 event->acceptProposedAction();
2128 } else {
2129 d->dropIndicatorRect = QRect();
2130 }
2131 break;
2132 case BelowItem:
2133 if (d->isIndexDropEnabled(index.parent())) {
2134 d->dropIndicatorRect = QRect(rect.left(), rect.bottom(), rect.width(), 0);
2135 event->acceptProposedAction();
2136 } else {
2137 d->dropIndicatorRect = QRect();
2138 }
2139 break;
2140 case OnItem:
2141 if (d->isIndexDropEnabled(index)) {
2142 d->dropIndicatorRect = rect;
2143 event->acceptProposedAction();
2144 } else {
2145 d->dropIndicatorRect = QRect();
2146 }
2147 break;
2148 case OnViewport:
2149 d->dropIndicatorRect = QRect();
2150 if (d->isIndexDropEnabled(rootIndex())) {
2151 event->acceptProposedAction(); // allow dropping in empty areas
2152 }
2153 break;
2154 }
2155 } else {
2156 d->dropIndicatorRect = QRect();
2157 d->dropIndicatorPosition = OnViewport;
2158 if (d->isIndexDropEnabled(rootIndex())) {
2159 event->acceptProposedAction(); // allow dropping in empty areas
2160 }
2161 }
2162 d->viewport->update();
2163 } // can drop
2164
2165 if (d->shouldAutoScroll(event->position().toPoint()))
2166 startAutoScroll();
2167}
2168
2169/*!
2170 \internal
2171 Return true if this is a move from ourself and \a index is a child of the selection that
2172 is being moved.
2173 */
2174bool QAbstractItemViewPrivate::droppingOnItself(QDropEvent *event, const QModelIndex &index)
2175{
2176 Q_Q(QAbstractItemView);
2177 Qt::DropAction dropAction = event->dropAction();
2178 if (q->dragDropMode() == QAbstractItemView::InternalMove)
2179 dropAction = Qt::MoveAction;
2180 if (event->source() == q
2181 && event->possibleActions() & Qt::MoveAction
2182 && dropAction == Qt::MoveAction) {
2183 QModelIndexList selectedIndexes = q->selectedIndexes();
2184 QModelIndex child = index;
2185 while (child.isValid() && child != root) {
2186 if (selectedIndexes.contains(child))
2187 return true;
2188 child = child.parent();
2189 }
2190 }
2191 return false;
2192}
2193
2194/*!
2195 \fn void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *event)
2196
2197 This function is called when the item being dragged leaves the view.
2198 The \a event describes the state of the drag and drop operation.
2199*/
2200void QAbstractItemView::dragLeaveEvent(QDragLeaveEvent *)
2201{
2202 Q_D(QAbstractItemView);
2203 stopAutoScroll();
2204 setState(NoState);
2205 d->hover = QModelIndex();
2206 d->viewport->update();
2207}
2208
2209/*!
2210 This function is called with the given \a event when a drop event occurs over
2211 the widget. If the model accepts the even position the drop event is accepted;
2212 otherwise it is ignored.
2213
2214 \sa startDrag()
2215*/
2216void QAbstractItemView::dropEvent(QDropEvent *event)
2217{
2218 Q_D(QAbstractItemView);
2219 if (dragDropMode() == InternalMove) {
2220 if (event->source() != this || !(event->possibleActions() & Qt::MoveAction))
2221 return;
2222 }
2223
2224 QModelIndex index;
2225 int col = -1;
2226 int row = -1;
2227 if (d->dropOn(event, &row, &col, &index)) {
2228 const Qt::DropAction action = dragDropMode() == InternalMove ? Qt::MoveAction : event->dropAction();
2229 if (d->model->dropMimeData(event->mimeData(), action, row, col, index)) {
2230 if (action != event->dropAction()) {
2231 event->setDropAction(action);
2232 event->accept();
2233 } else {
2234 event->acceptProposedAction();
2235 }
2236 }
2237 }
2238 stopAutoScroll();
2239 setState(NoState);
2240 d->viewport->update();
2241}
2242
2243/*!
2244 If the event hasn't already been accepted, determines the index to drop on.
2245
2246 if (row == -1 && col == -1)
2247 // append to this drop index
2248 else
2249 // place at row, col in drop index
2250
2251 If it returns \c true a drop can be done, and dropRow, dropCol and dropIndex reflects the position of the drop.
2252 \internal
2253 */
2254bool QAbstractItemViewPrivate::dropOn(QDropEvent *event, int *dropRow, int *dropCol, QModelIndex *dropIndex)
2255{
2256 Q_Q(QAbstractItemView);
2257 if (event->isAccepted())
2258 return false;
2259
2260 QModelIndex index;
2261 // rootIndex() (i.e. the viewport) might be a valid index
2262 if (viewport->rect().contains(event->position().toPoint())) {
2263 index = q->indexAt(event->position().toPoint());
2264 if (!index.isValid())
2265 index = root;
2266 }
2267
2268 // If we are allowed to do the drop
2269 if (model->supportedDropActions() & event->dropAction()) {
2270 int row = -1;
2271 int col = -1;
2272 if (index != root) {
2273 dropIndicatorPosition = position(event->position().toPoint(), q->visualRect(index), index);
2274 switch (dropIndicatorPosition) {
2275 case QAbstractItemView::AboveItem:
2276 row = index.row();
2277 col = index.column();
2278 index = index.parent();
2279 break;
2280 case QAbstractItemView::BelowItem:
2281 row = index.row() + 1;
2282 col = index.column();
2283 index = index.parent();
2284 break;
2285 case QAbstractItemView::OnItem:
2286 case QAbstractItemView::OnViewport:
2287 break;
2288 }
2289 } else {
2290 dropIndicatorPosition = QAbstractItemView::OnViewport;
2291 }
2292 *dropIndex = index;
2293 *dropRow = row;
2294 *dropCol = col;
2295 if (!droppingOnItself(event, index))
2296 return true;
2297 }
2298 return false;
2299}
2300
2301QAbstractItemView::DropIndicatorPosition
2302QAbstractItemViewPrivate::position(const QPoint &pos, const QRect &rect, const QModelIndex &index) const
2303{
2304 QAbstractItemView::DropIndicatorPosition r = QAbstractItemView::OnViewport;
2305 if (!overwrite) {
2306 const int margin = qBound(2, qRound(qreal(rect.height()) / 5.5), 12);
2307 if (pos.y() - rect.top() < margin) {
2308 r = QAbstractItemView::AboveItem;
2309 } else if (rect.bottom() - pos.y() < margin) {
2310 r = QAbstractItemView::BelowItem;
2311 } else if (rect.contains(pos, true)) {
2312 r = QAbstractItemView::OnItem;
2313 }
2314 } else {
2315 QRect touchingRect = rect;
2316 touchingRect.adjust(-1, -1, 1, 1);
2317 if (touchingRect.contains(pos, false)) {
2318 r = QAbstractItemView::OnItem;
2319 }
2320 }
2321
2322 if (r == QAbstractItemView::OnItem && (!(model->flags(index) & Qt::ItemIsDropEnabled)))
2323 r = pos.y() < rect.center().y() ? QAbstractItemView::AboveItem : QAbstractItemView::BelowItem;
2324
2325 return r;
2326}
2327
2328#endif // QT_CONFIG(draganddrop)
2329
2330/*!
2331 This function is called with the given \a event when the widget obtains the focus.
2332 By default, the event is ignored.
2333
2334 \sa setFocus(), focusOutEvent()
2335*/
2336void QAbstractItemView::focusInEvent(QFocusEvent *event)
2337{
2338 Q_D(QAbstractItemView);
2339 QAbstractScrollArea::focusInEvent(event);
2340
2341 const QItemSelectionModel* model = selectionModel();
2342 bool currentIndexValid = currentIndex().isValid();
2343
2344 if (model
2345 && !d->currentIndexSet
2346 && !currentIndexValid) {
2347 bool autoScroll = d->autoScroll;
2348 d->autoScroll = false;
2349 QModelIndex index = moveCursor(MoveNext, Qt::NoModifier); // first visible index
2350 if (index.isValid() && d->isIndexEnabled(index) && event->reason() != Qt::MouseFocusReason) {
2351 selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
2352 currentIndexValid = true;
2353 }
2354 d->autoScroll = autoScroll;
2355 }
2356
2357 if (model && currentIndexValid)
2358 setAttribute(Qt::WA_InputMethodEnabled, (currentIndex().flags() & Qt::ItemIsEditable));
2359 else if (!currentIndexValid)
2360 setAttribute(Qt::WA_InputMethodEnabled, false);
2361
2362 d->viewport->update();
2363}
2364
2365/*!
2366 This function is called with the given \a event when the widget
2367 loses the focus. By default, the event is ignored.
2368
2369 \sa clearFocus(), focusInEvent()
2370*/
2371void QAbstractItemView::focusOutEvent(QFocusEvent *event)
2372{
2373 Q_D(QAbstractItemView);
2374 QAbstractScrollArea::focusOutEvent(event);
2375 d->viewport->update();
2376}
2377
2378/*!
2379 This function is called with the given \a event when a key event is sent to
2380 the widget. The default implementation handles basic cursor movement, e.g. Up,
2381 Down, Left, Right, Home, PageUp, and PageDown; the activated() signal is
2382 emitted if the current index is valid and the activation key is pressed
2383 (e.g. Enter or Return, depending on the platform).
2384 This function is where editing is initiated by key press, e.g. if F2 is
2385 pressed.
2386
2387 \sa edit(), moveCursor(), keyboardSearch(), tabKeyNavigation
2388*/
2389void QAbstractItemView::keyPressEvent(QKeyEvent *event)
2390{
2391 Q_D(QAbstractItemView);
2392 d->delayedAutoScroll.stop(); //any interaction with the view cancel the auto scrolling
2393
2394#if !defined(QT_NO_CLIPBOARD) && !defined(QT_NO_SHORTCUT)
2395 if (event == QKeySequence::Copy) {
2396 const QModelIndex index = currentIndex();
2397 if (index.isValid() && d->model) {
2398 const QVariant variant = d->model->data(index, Qt::DisplayRole);
2399 if (variant.canConvert<QString>())
2400 QGuiApplication::clipboard()->setText(variant.toString());
2401 }
2402 event->accept();
2403 }
2404#endif
2405
2406 QPersistentModelIndex newCurrent;
2407 d->moveCursorUpdatedView = false;
2408 switch (event->key()) {
2409 case Qt::Key_Down:
2410 newCurrent = moveCursor(MoveDown, event->modifiers());
2411 break;
2412 case Qt::Key_Up:
2413 newCurrent = moveCursor(MoveUp, event->modifiers());
2414 break;
2415 case Qt::Key_Left:
2416 newCurrent = moveCursor(MoveLeft, event->modifiers());
2417 break;
2418 case Qt::Key_Right:
2419 newCurrent = moveCursor(MoveRight, event->modifiers());
2420 break;
2421 case Qt::Key_Home:
2422 newCurrent = moveCursor(MoveHome, event->modifiers());
2423 break;
2424 case Qt::Key_End:
2425 newCurrent = moveCursor(MoveEnd, event->modifiers());
2426 break;
2427 case Qt::Key_PageUp:
2428 newCurrent = moveCursor(MovePageUp, event->modifiers());
2429 break;
2430 case Qt::Key_PageDown:
2431 newCurrent = moveCursor(MovePageDown, event->modifiers());
2432 break;
2433 case Qt::Key_Tab:
2434 if (d->tabKeyNavigation)
2435 newCurrent = moveCursor(MoveNext, event->modifiers());
2436 break;
2437 case Qt::Key_Backtab:
2438 if (d->tabKeyNavigation)
2439 newCurrent = moveCursor(MovePrevious, event->modifiers());
2440 break;
2441 }
2442
2443 QPersistentModelIndex oldCurrent = currentIndex();
2444 if (newCurrent != oldCurrent && newCurrent.isValid() && d->isIndexEnabled(newCurrent)) {
2445 if (!hasFocus() && QApplication::focusWidget() == indexWidget(oldCurrent))
2446 setFocus();
2447 QItemSelectionModel::SelectionFlags command = selectionCommand(newCurrent, event);
2448 if (command != QItemSelectionModel::NoUpdate
2449 || style()->styleHint(QStyle::SH_ItemView_MovementWithoutUpdatingSelection, nullptr, this)) {
2450 // note that we don't check if the new current index is enabled because moveCursor() makes sure it is
2451 if (command & QItemSelectionModel::Current) {
2452 d->selectionModel->setCurrentIndex(newCurrent, QItemSelectionModel::NoUpdate);
2453 if (!d->currentSelectionStartIndex.isValid())
2454 d->currentSelectionStartIndex = oldCurrent;
2455 QRect rect(visualRect(d->currentSelectionStartIndex).center(), visualRect(newCurrent).center());
2456 setSelection(rect, command);
2457 } else {
2458 d->selectionModel->setCurrentIndex(newCurrent, command);
2459 d->currentSelectionStartIndex = newCurrent;
2460 if (newCurrent.isValid()) {
2461 // We copy the same behaviour as for mousePressEvent().
2462 QRect rect(visualRect(newCurrent).center(), QSize(1, 1));
2463 setSelection(rect, command);
2464 }
2465 }
2466 event->accept();
2467 return;
2468 }
2469 }
2470
2471 switch (event->key()) {
2472 // ignored keys
2473 case Qt::Key_Down:
2474 case Qt::Key_Up:
2475 case Qt::Key_Left:
2476 case Qt::Key_Right:
2477 case Qt::Key_Home:
2478 case Qt::Key_End:
2479 case Qt::Key_PageUp:
2480 case Qt::Key_PageDown:
2481 case Qt::Key_Escape:
2482 case Qt::Key_Shift:
2483 case Qt::Key_Control:
2484 case Qt::Key_Delete:
2485 case Qt::Key_Backspace:
2486 event->ignore();
2487 break;
2488 case Qt::Key_Space:
2489 case Qt::Key_Select:
2490 if (!edit(currentIndex(), AnyKeyPressed, event)) {
2491 if (d->selectionModel)
2492 d->selectionModel->select(currentIndex(), selectionCommand(currentIndex(), event));
2493 if (event->key() == Qt::Key_Space) {
2494 keyboardSearch(event->text());
2495 event->accept();
2496 }
2497 }
2498 break;
2499#ifdef Q_OS_MACOS
2500 case Qt::Key_Enter:
2501 case Qt::Key_Return:
2502 // Propagate the enter if you couldn't edit the item and there are no
2503 // current editors (if there are editors, the event was most likely propagated from it).
2504 if (!edit(currentIndex(), EditKeyPressed, event) && d->editorIndexHash.isEmpty())
2505 event->ignore();
2506 break;
2507#else
2508 case Qt::Key_F2:
2509 if (!edit(currentIndex(), EditKeyPressed, event))
2510 event->ignore();
2511 break;
2512 case Qt::Key_Enter:
2513 case Qt::Key_Return:
2514 // ### we can't open the editor on enter, because
2515 // some widgets will forward the enter event back
2516 // to the viewport, starting an endless loop
2517 if (state() != EditingState || hasFocus()) {
2518 if (currentIndex().isValid())
2519 emit activated(currentIndex());
2520 event->ignore();
2521 }
2522 break;
2523#endif
2524 default: {
2525#ifndef QT_NO_SHORTCUT
2526 if (event == QKeySequence::SelectAll && selectionMode() != NoSelection) {
2527 selectAll();
2528 break;
2529 }
2530#endif
2531#ifdef Q_OS_MACOS
2532 if (event->key() == Qt::Key_O && event->modifiers() & Qt::ControlModifier && currentIndex().isValid()) {
2533 emit activated(currentIndex());
2534 break;
2535 }
2536#endif
2537 bool modified = (event->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier));
2538 if (!event->text().isEmpty() && !modified && !edit(currentIndex(), AnyKeyPressed, event)) {
2539 keyboardSearch(event->text());
2540 event->accept();
2541 } else {
2542 event->ignore();
2543 }
2544 break; }
2545 }
2546 if (d->moveCursorUpdatedView)
2547 event->accept();
2548}
2549
2550/*!
2551 This function is called with the given \a event when a resize event is sent to
2552 the widget.
2553
2554 \sa QWidget::resizeEvent()
2555*/
2556void QAbstractItemView::resizeEvent(QResizeEvent *event)
2557{
2558 QAbstractScrollArea::resizeEvent(event);
2559 updateGeometries();
2560}
2561
2562/*!
2563 This function is called with the given \a event when a timer event is sent
2564 to the widget.
2565
2566 \sa QObject::timerEvent()
2567*/
2568void QAbstractItemView::timerEvent(QTimerEvent *event)
2569{
2570 Q_D(QAbstractItemView);
2571 if (event->timerId() == d->fetchMoreTimer.timerId())
2572 d->fetchMore();
2573 else if (event->timerId() == d->delayedReset.timerId())
2574 reset();
2575 else if (event->timerId() == d->autoScrollTimer.timerId())
2576 doAutoScroll();
2577 else if (event->timerId() == d->updateTimer.timerId())
2578 d->updateDirtyRegion();
2579 else if (event->timerId() == d->delayedEditing.timerId()) {
2580 d->delayedEditing.stop();
2581 edit(currentIndex());
2582 } else if (event->timerId() == d->delayedLayout.timerId()) {
2583 d->delayedLayout.stop();
2584 if (isVisible()) {
2585 d->interruptDelayedItemsLayout();
2586 doItemsLayout();
2587 const QModelIndex current = currentIndex();
2588 if (current.isValid() && d->state == QAbstractItemView::EditingState)
2589 scrollTo(current);
2590 }
2591 } else if (event->timerId() == d->delayedAutoScroll.timerId()) {
2592 d->delayedAutoScroll.stop();
2593 //end of the timer: if the current item is still the same as the one when the mouse press occurred
2594 //we only get here if there was no double click
2595 if (d->pressedIndex.isValid() && d->pressedIndex == currentIndex())
2596 scrollTo(d->pressedIndex);
2597 } else if (event->timerId() == d->pressClosedEditorWatcher.timerId()) {
2598 d->pressClosedEditorWatcher.stop();
2599 }
2600}
2601
2602/*!
2603 \reimp
2604*/
2605void QAbstractItemView::inputMethodEvent(QInputMethodEvent *event)
2606{
2607 Q_D(QAbstractItemView);
2608 // When QAbstractItemView::AnyKeyPressed is used, a new IM composition might
2609 // start before the editor widget acquires focus. Changing focus would interrupt
2610 // the composition, so we keep focus on the view until that first composition
2611 // is complete, and pass QInputMethoEvents on to the editor widget so that the
2612 // user gets the expected feedback. See also inputMethodQuery, which redirects
2613 // calls to the editor widget during that period.
2614 bool forwardEventToEditor = false;
2615 const bool commit = !event->commitString().isEmpty();
2616 const bool preediting = !event->preeditString().isEmpty();
2617 if (QWidget *currentEditor = d->editorForIndex(currentIndex()).widget) {
2618 if (d->waitForIMCommit) {
2619 if (commit || !preediting) {
2620 // commit or cancel
2621 d->waitForIMCommit = false;
2622 QApplication::sendEvent(currentEditor, event);
2623 if (!commit) {
2624 QAbstractItemDelegate *delegate = itemDelegateForIndex(currentIndex());
2625 if (delegate)
2626 delegate->setEditorData(currentEditor, currentIndex());
2627 d->selectAllInEditor(currentEditor);
2628 }
2629 if (currentEditor->focusPolicy() != Qt::NoFocus)
2630 currentEditor->setFocus();
2631 } else {
2632 // more pre-editing
2633 QApplication::sendEvent(currentEditor, event);
2634 }
2635 return;
2636 }
2637 } else if (preediting) {
2638 // don't set focus when the editor opens
2639 d->waitForIMCommit = true;
2640 // but pass preedit on to editor
2641 forwardEventToEditor = true;
2642 } else if (!commit) {
2643 event->ignore();
2644 return;
2645 }
2646 if (!edit(currentIndex(), AnyKeyPressed, event)) {
2647 d->waitForIMCommit = false;
2648 if (commit)
2649 keyboardSearch(event->commitString());
2650 event->ignore();
2651 } else if (QWidget *currentEditor; forwardEventToEditor
2652 && (currentEditor = d->editorForIndex(currentIndex()).widget)) {
2653 QApplication::sendEvent(currentEditor, event);
2654 }
2655}
2656
2657#if QT_CONFIG(draganddrop)
2658/*!
2659 \enum QAbstractItemView::DropIndicatorPosition
2660
2661 This enum indicates the position of the drop indicator in
2662 relation to the index at the current mouse position:
2663
2664 \value OnItem The item will be dropped on the index.
2665
2666 \value AboveItem The item will be dropped above the index.
2667
2668 \value BelowItem The item will be dropped below the index.
2669
2670 \value OnViewport The item will be dropped onto a region of the viewport with
2671 no items. The way each view handles items dropped onto the viewport depends on
2672 the behavior of the underlying model in use.
2673*/
2674
2675
2676/*!
2677 Returns the position of the drop indicator in relation to the closest item.
2678*/
2679QAbstractItemView::DropIndicatorPosition QAbstractItemView::dropIndicatorPosition() const
2680{
2681 Q_D(const QAbstractItemView);
2682 return d->dropIndicatorPosition;
2683}
2684#endif
2685
2686/*!
2687 This convenience function returns a list of all selected and
2688 non-hidden item indexes in the view. The list contains no
2689 duplicates, and is not sorted.
2690
2691 The view calls this function to decide which items operations such as
2692 drag and drop act on, and view classes reimplement it to leave out
2693 indexes they don't display, such as hidden rows and columns. To get the
2694 complete selection from outside the view, including hidden items, call
2695 QItemSelectionModel::selectedIndexes() on the view's selectionModel().
2696
2697 \sa QItemSelectionModel::selectedIndexes()
2698*/
2699QModelIndexList QAbstractItemView::selectedIndexes() const
2700{
2701 Q_D(const QAbstractItemView);
2702 QModelIndexList indexes;
2703 if (d->selectionModel) {
2704 indexes = d->selectionModel->selectedIndexes();
2705 auto isHidden = [this](const QModelIndex &idx) {
2706 return isIndexHidden(idx);
2707 };
2708 indexes.removeIf(isHidden);
2709 }
2710 return indexes;
2711}
2712
2713/*!
2714 Starts editing the item at \a index, creating an editor if
2715 necessary, and returns \c true if the view's \l{State} is now
2716 EditingState; otherwise returns \c false.
2717
2718 The action that caused the editing process is described by
2719 \a trigger, and the associated event is specified by \a event.
2720
2721 Editing can be forced by specifying the \a trigger to be
2722 QAbstractItemView::AllEditTriggers.
2723
2724 \sa closeEditor()
2725*/
2726bool QAbstractItemView::edit(const QModelIndex &index, EditTrigger trigger, QEvent *event)
2727{
2728 Q_D(QAbstractItemView);
2729
2730 if (!d->isIndexValid(index))
2731 return false;
2732
2733 if (QWidget *w = (d->persistent.isEmpty() ? static_cast<QWidget*>(nullptr) : d->editorForIndex(index).widget.data())) {
2734 if (w->focusPolicy() == Qt::NoFocus)
2735 return false;
2736 if (!d->waitForIMCommit)
2737 w->setFocus();
2738 else
2739 updateMicroFocus();
2740 return true;
2741 }
2742
2743 if (trigger == DoubleClicked) {
2744 d->delayedEditing.stop();
2745 d->delayedAutoScroll.stop();
2746 } else if (trigger == CurrentChanged) {
2747 d->delayedEditing.stop();
2748 }
2749
2750 // in case e.g. setData() triggers a reset()
2751 QPersistentModelIndex safeIndex(index);
2752
2753 if (d->sendDelegateEvent(index, event)) {
2754 update(safeIndex);
2755 return true;
2756 }
2757
2758 if (!safeIndex.isValid()) {
2759 return false;
2760 }
2761
2762 // save the previous trigger before updating
2763 EditTriggers lastTrigger = d->lastTrigger;
2764 d->lastTrigger = trigger;
2765
2766 if (!d->shouldEdit(trigger, d->model->buddy(safeIndex)))
2767 return false;
2768
2769 if (d->delayedEditing.isActive())
2770 return false;
2771
2772 // we will receive a mouseButtonReleaseEvent after a
2773 // mouseDoubleClickEvent, so we need to check the previous trigger
2774 if (lastTrigger == DoubleClicked && trigger == SelectedClicked)
2775 return false;
2776
2777 // we may get a double click event later
2778 if (trigger == SelectedClicked)
2779 d->delayedEditing.start(QApplication::doubleClickInterval(), this);
2780 else
2781 d->openEditor(safeIndex, d->shouldForwardEvent(trigger, event) ? event : nullptr);
2782
2783 return true;
2784}
2785
2786/*!
2787 \internal
2788 Updates the data shown in the open editor widgets in the view.
2789*/
2790void QAbstractItemView::updateEditorData()
2791{
2792 Q_D(QAbstractItemView);
2793 d->updateEditorData(QModelIndex(), QModelIndex());
2794}
2795
2796/*!
2797 \internal
2798 Updates the geometry of the open editor widgets in the view.
2799*/
2800void QAbstractItemView::updateEditorGeometries()
2801{
2802 Q_D(QAbstractItemView);
2803 if (d->editorIndexHash.isEmpty())
2804 return;
2805 if (d->delayedPendingLayout) {
2806 // doItemsLayout() will end up calling this function again
2807 d->executePostedLayout();
2808 return;
2809 }
2810 QStyleOptionViewItem option;
2811 initViewItemOption(&option);
2812 QEditorIndexHash::iterator it = d->editorIndexHash.begin();
2813 QWidgetList editorsToRelease;
2814 QWidgetList editorsToHide;
2815 while (it != d->editorIndexHash.end()) {
2816 QModelIndex index = it.value();
2817 QWidget *editor = it.key();
2818 if (index.isValid() && editor) {
2819 option.rect = visualRect(index);
2820 if (option.rect.isValid()) {
2821 editor->show();
2822 QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
2823 if (delegate)
2824 delegate->updateEditorGeometry(editor, option, index);
2825 } else {
2826 editorsToHide << editor;
2827 }
2828 ++it;
2829 } else {
2830 d->indexEditorHash.remove(it.value());
2831 it = d->editorIndexHash.erase(it);
2832 editorsToRelease << editor;
2833 }
2834 }
2835
2836 //we hide and release the editor outside of the loop because it might change the focus and try
2837 //to change the editors hashes.
2838 for (QWidget *editor : std::as_const(editorsToHide))
2839 editor->hide();
2840 for (QWidget *editor : std::as_const(editorsToRelease))
2841 d->releaseEditor(editor);
2842}
2843
2844/*!
2845 Updates the geometry of the child widgets of the view.
2846*/
2847void QAbstractItemView::updateGeometries()
2848{
2849 Q_D(QAbstractItemView);
2850 updateEditorGeometries();
2851 d->fetchMoreTimer.start(0, this); //fetch more later
2852 d->updateGeometry();
2853}
2854
2855/*!
2856 \internal
2857*/
2858void QAbstractItemView::verticalScrollbarValueChanged(int value)
2859{
2860 Q_D(QAbstractItemView);
2861 if (verticalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
2862 d->model->fetchMore(d->root);
2863 QPoint posInVp = viewport()->mapFromGlobal(QCursor::pos());
2864 if (viewport()->rect().contains(posInVp))
2865 d->checkMouseMove(posInVp);
2866}
2867
2868/*!
2869 \internal
2870*/
2871void QAbstractItemView::horizontalScrollbarValueChanged(int value)
2872{
2873 Q_D(QAbstractItemView);
2874 if (horizontalScrollBar()->maximum() == value && d->model->canFetchMore(d->root))
2875 d->model->fetchMore(d->root);
2876 QPoint posInVp = viewport()->mapFromGlobal(QCursor::pos());
2877 if (viewport()->rect().contains(posInVp))
2878 d->checkMouseMove(posInVp);
2879}
2880
2881/*!
2882 \internal
2883*/
2884void QAbstractItemView::verticalScrollbarAction(int)
2885{
2886 //do nothing
2887}
2888
2889/*!
2890 \internal
2891*/
2892void QAbstractItemView::horizontalScrollbarAction(int)
2893{
2894 //do nothing
2895}
2896
2897/*!
2898 Closes the given \a editor, and releases it. The \a hint is
2899 used to specify how the view should respond to the end of the editing
2900 operation. For example, the hint may indicate that the next item in
2901 the view should be opened for editing.
2902
2903 \sa edit(), commitData()
2904*/
2905
2906void QAbstractItemView::closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint)
2907{
2908 Q_D(QAbstractItemView);
2909
2910 // Close the editor
2911 if (editor) {
2912 const bool isPersistent = d->persistent.contains(editor);
2913 const QModelIndex index = d->indexForEditor(editor);
2914 if (!index.isValid()) {
2915 if (!editor->isVisible()) {
2916 // The commit might have removed the index (e.g. it might get filtered), in
2917 // which case the editor is already hidden and scheduled for deletion. We
2918 // don't have to do anything, except reset the state, and continue with
2919 // EndEditHint processing.
2920 if (!isPersistent)
2921 setState(NoState);
2922 } else {
2923 qCWarning(lcAIV,
2924 "QAbstractItemView::closeEditor called with an editor that does not "
2925 "belong to this view");
2926 return;
2927 }
2928 } else {
2929 const bool hadFocus = editor->hasFocus();
2930 // start a timer that expires immediately when we return to the event loop
2931 // to identify whether this close was triggered by a mousepress-initiated
2932 // focus event
2933 d->pressClosedEditorWatcher.start(0, this);
2934 d->lastEditedIndex = index;
2935
2936 if (!isPersistent) {
2937 setState(NoState);
2938 QModelIndex index = d->indexForEditor(editor);
2939 editor->removeEventFilter(itemDelegateForIndex(index));
2940 d->removeEditor(editor);
2941 }
2942 if (hadFocus) {
2943 if (focusPolicy() != Qt::NoFocus)
2944 setFocus(); // this will send a focusLost event to the editor
2945 else
2946 editor->clearFocus();
2947 } else {
2948 d->checkPersistentEditorFocus();
2949 }
2950
2951 QPointer<QWidget> ed = editor;
2952 QCoreApplication::sendPostedEvents(editor, 0);
2953 editor = ed;
2954
2955 if (!isPersistent && editor)
2956 d->releaseEditor(editor, index);
2957 }
2958 }
2959
2960 // The EndEditHint part
2961 QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::NoUpdate;
2962 if (d->selectionMode != NoSelection)
2963 flags = QItemSelectionModel::ClearAndSelect | d->selectionBehaviorFlags();
2964 switch (hint) {
2965 case QAbstractItemDelegate::EditNextItem: {
2966 QModelIndex index = moveCursor(MoveNext, Qt::NoModifier);
2967 if (index.isValid()) {
2968 QPersistentModelIndex persistent(index);
2969 d->selectionModel->setCurrentIndex(persistent, flags);
2970 // currentChanged signal would have already started editing
2971 if (index.flags() & Qt::ItemIsEditable
2972 && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
2973 edit(persistent);
2974 } break; }
2975 case QAbstractItemDelegate::EditPreviousItem: {
2976 QModelIndex index = moveCursor(MovePrevious, Qt::NoModifier);
2977 if (index.isValid()) {
2978 QPersistentModelIndex persistent(index);
2979 d->selectionModel->setCurrentIndex(persistent, flags);
2980 // currentChanged signal would have already started editing
2981 if (index.flags() & Qt::ItemIsEditable
2982 && (!(editTriggers() & QAbstractItemView::CurrentChanged)))
2983 edit(persistent);
2984 } break; }
2985 case QAbstractItemDelegate::SubmitModelCache:
2986 d->model->submit();
2987 break;
2988 case QAbstractItemDelegate::RevertModelCache:
2989 d->model->revert();
2990 break;
2991 default:
2992 break;
2993 }
2994}
2995
2996/*!
2997 Commit the data in the \a editor to the model.
2998
2999 \sa closeEditor()
3000*/
3001void QAbstractItemView::commitData(QWidget *editor)
3002{
3003 Q_D(QAbstractItemView);
3004 if (!editor || !d->itemDelegate || d->currentlyCommittingEditor)
3005 return;
3006 QModelIndex index = d->indexForEditor(editor);
3007 if (!index.isValid()) {
3008 qCWarning(lcAIV,
3009 "QAbstractItemView::commitData called with an editor that does not belong to "
3010 "this view");
3011 return;
3012 }
3013 d->currentlyCommittingEditor = editor;
3014 QAbstractItemDelegate *delegate = itemDelegateForIndex(index);
3015 editor->removeEventFilter(delegate);
3016 delegate->setModelData(editor, d->model, index);
3017 editor->installEventFilter(delegate);
3018 d->currentlyCommittingEditor = nullptr;
3019}
3020
3021/*!
3022 This function is called when the given \a editor has been destroyed.
3023
3024 \sa closeEditor()
3025*/
3026void QAbstractItemView::editorDestroyed(QObject *editor)
3027{
3028 Q_D(QAbstractItemView);
3029 QWidget *w = qobject_cast<QWidget*>(editor);
3030 d->removeEditor(w);
3031 d->persistent.remove(w);
3032 if (state() == EditingState)
3033 setState(NoState);
3034}
3035
3036
3037
3038/*!
3039 Moves to and selects the item best matching the string \a search.
3040 If no item is found nothing happens.
3041
3042 In the default implementation, the search is reset if \a search is empty, or
3043 the time interval since the last search has exceeded
3044 QApplication::keyboardInputInterval().
3045*/
3046void QAbstractItemView::keyboardSearch(const QString &search)
3047{
3048 Q_D(QAbstractItemView);
3049 if (!d->model->rowCount(d->root) || !d->model->columnCount(d->root))
3050 return;
3051
3052 QModelIndex start = currentIndex().isValid() ? currentIndex()
3053 : d->model->index(0, 0, d->root);
3054 bool skipRow = false;
3055 bool keyboardTimeWasValid = d->keyboardInputTime.isValid();
3056 qint64 keyboardInputTimeElapsed;
3057 if (keyboardTimeWasValid)
3058 keyboardInputTimeElapsed = d->keyboardInputTime.restart();
3059 else
3060 d->keyboardInputTime.start();
3061 if (search.isEmpty() || !keyboardTimeWasValid
3062 || keyboardInputTimeElapsed > QApplication::keyboardInputInterval()) {
3063 d->keyboardInput = search;
3064 skipRow = currentIndex().isValid(); //if it is not valid we should really start at QModelIndex(0,0)
3065 } else {
3066 d->keyboardInput += search;
3067 }
3068
3069 // special case for searches with same key like 'aaaaa'
3070 bool sameKey = false;
3071 if (d->keyboardInput.size() > 1) {
3072 int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.size() - 1));
3073 sameKey = (c == d->keyboardInput.size());
3074 if (sameKey)
3075 skipRow = true;
3076 }
3077
3078 // skip if we are searching for the same key or a new search started
3079 if (skipRow) {
3080 QModelIndex parent = start.parent();
3081 int newRow = (start.row() < d->model->rowCount(parent) - 1) ? start.row() + 1 : 0;
3082 start = d->model->index(newRow, start.column(), parent);
3083 }
3084
3085 // search from start with wraparound
3086 QModelIndex current = start;
3087 QModelIndexList match;
3088 QModelIndex firstMatch;
3089 QModelIndex startMatch;
3090 QModelIndexList previous;
3091 do {
3092 match = d->model->match(current, Qt::DisplayRole, d->keyboardInput, 1,
3093 d->keyboardSearchFlags);
3094 if (match == previous)
3095 break;
3096 firstMatch = match.value(0);
3097 previous = match;
3098 if (firstMatch.isValid()) {
3099 if (d->isIndexEnabled(firstMatch)) {
3100 setCurrentIndex(firstMatch);
3101 break;
3102 }
3103 int row = firstMatch.row() + 1;
3104 if (row >= d->model->rowCount(firstMatch.parent()))
3105 row = 0;
3106 current = firstMatch.sibling(row, firstMatch.column());
3107
3108 //avoid infinite loop if all the matching items are disabled.
3109 if (!startMatch.isValid())
3110 startMatch = firstMatch;
3111 else if (startMatch == firstMatch)
3112 break;
3113 }
3114 } while (current != start && firstMatch.isValid());
3115}
3116
3117/*!
3118 Returns the size hint for the item with the specified \a index or
3119 an invalid size for invalid indexes.
3120
3121 \sa sizeHintForRow(), sizeHintForColumn()
3122*/
3123QSize QAbstractItemView::sizeHintForIndex(const QModelIndex &index) const
3124{
3125 Q_D(const QAbstractItemView);
3126 if (!d->isIndexValid(index))
3127 return QSize();
3128 const auto delegate = itemDelegateForIndex(index);
3129 QStyleOptionViewItem option;
3130 initViewItemOption(&option);
3131 return delegate ? delegate->sizeHint(option, index) : QSize();
3132}
3133
3134/*!
3135 Returns the height size hint for the specified \a row or -1 if
3136 there is no model.
3137
3138 The returned height is calculated using the size hints of the
3139 given \a row's items, i.e. the returned value is the maximum
3140 height among the items. Note that to control the height of a row,
3141 you must reimplement the QAbstractItemDelegate::sizeHint()
3142 function.
3143
3144 This function is used in views with a vertical header to find the
3145 size hint for a header section based on the contents of the given
3146 \a row.
3147
3148 \sa sizeHintForColumn()
3149*/
3150int QAbstractItemView::sizeHintForRow(int row) const
3151{
3152 Q_D(const QAbstractItemView);
3153
3154 if (row < 0 || row >= d->model->rowCount(d->root))
3155 return -1;
3156
3157 ensurePolished();
3158
3159 QStyleOptionViewItem option;
3160 initViewItemOption(&option);
3161 int height = 0;
3162 int colCount = d->model->columnCount(d->root);
3163 for (int c = 0; c < colCount; ++c) {
3164 const QModelIndex index = d->model->index(row, c, d->root);
3165 if (QWidget *editor = d->editorForIndex(index).widget.data())
3166 height = qMax(height, editor->height());
3167 if (const QAbstractItemDelegate *delegate = itemDelegateForIndex(index))
3168 height = qMax(height, delegate->sizeHint(option, index).height());
3169 }
3170 return height;
3171}
3172
3173/*!
3174 Returns the width size hint for the specified \a column or -1 if there is no model.
3175
3176 This function is used in views with a horizontal header to find the size hint for
3177 a header section based on the contents of the given \a column.
3178
3179 \sa sizeHintForRow()
3180*/
3181int QAbstractItemView::sizeHintForColumn(int column) const
3182{
3183 Q_D(const QAbstractItemView);
3184
3185 if (column < 0 || column >= d->model->columnCount(d->root))
3186 return -1;
3187
3188 ensurePolished();
3189
3190 QStyleOptionViewItem option;
3191 initViewItemOption(&option);
3192 int width = 0;
3193 int rows = d->model->rowCount(d->root);
3194 for (int r = 0; r < rows; ++r) {
3195 const QModelIndex index = d->model->index(r, column, d->root);
3196 if (QWidget *editor = d->editorForIndex(index).widget.data())
3197 width = qMax(width, editor->sizeHint().width());
3198 if (const QAbstractItemDelegate *delegate = itemDelegateForIndex(index))
3199 width = qMax(width, delegate->sizeHint(option, index).width());
3200 }
3201 return width;
3202}
3203
3204/*!
3205 \property QAbstractItemView::updateThreshold
3206 \since 6.9
3207 This property holds the amount of changed indexes to directly trigger
3208 a full update of the view inside dataChanged().
3209
3210 The algorithm inside dataChanged() tries to minimize a full update of the
3211 view by calculating if the changed indexes are visible or not. For very
3212 large models, with a lot of large changes, this might take longer than the
3213 actual update so it's counter-productive. This property gives the ability
3214 to control the algorithm to skip the check and directly trigger a full
3215 update when the amount of changed indexes exceeds the given value.
3216
3217 The default value is 200.
3218
3219 \sa dataChanged()
3220*/
3221int QAbstractItemView::updateThreshold() const
3222{
3223 Q_D(const QAbstractItemView);
3224 return d->updateThreshold;
3225}
3226
3227void QAbstractItemView::setUpdateThreshold(int threshold)
3228{
3229 Q_D(QAbstractItemView);
3230 if (d->updateThreshold == threshold)
3231 return;
3232 d->updateThreshold = threshold;
3233}
3234
3235/*!
3236 \property QAbstractItemView::keyboardSearchFlags
3237 \since 6.11
3238 This property determines how the default implementation of
3239 keyboardSearch() matches the given string against the model's data.
3240
3241 The default value is \c{Qt::MatchStartsWith|Qt::MatchWrap}.
3242
3243 \sa keyboardSearch()
3244 \sa QAbstractItemModel::match()
3245*/
3246
3247Qt::MatchFlags QAbstractItemView::keyboardSearchFlags() const
3248{
3249 Q_D(const QAbstractItemView);
3250 return d->keyboardSearchFlags;
3251}
3252
3253void QAbstractItemView::setKeyboardSearchFlags(Qt::MatchFlags searchFlags)
3254{
3255 Q_D(QAbstractItemView);
3256 d->keyboardSearchFlags = searchFlags;
3257}
3258
3259/*!
3260 Opens a persistent editor on the item at the given \a index.
3261 If no editor exists, the delegate will create a new editor.
3262
3263 \sa closePersistentEditor(), isPersistentEditorOpen()
3264*/
3265void QAbstractItemView::openPersistentEditor(const QModelIndex &index)
3266{
3267 Q_D(QAbstractItemView);
3268 QStyleOptionViewItem options;
3269 initViewItemOption(&options);
3270 options.rect = visualRect(index);
3271 options.state |= (index == currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
3272
3273 QWidget *editor = d->editor(index, options);
3274 if (editor) {
3275 editor->show();
3276 d->persistent.insert(editor);
3277 }
3278}
3279
3280/*!
3281 Closes the persistent editor for the item at the given \a index.
3282
3283 \sa openPersistentEditor(), isPersistentEditorOpen()
3284*/
3285void QAbstractItemView::closePersistentEditor(const QModelIndex &index)
3286{
3287 Q_D(QAbstractItemView);
3288 if (QWidget *editor = d->editorForIndex(index).widget.data()) {
3289 if (index == selectionModel()->currentIndex())
3290 closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
3291 d->persistent.remove(editor);
3292 d->removeEditor(editor);
3293 d->releaseEditor(editor, index);
3294 }
3295}
3296
3297/*!
3298 \since 5.10
3299
3300 Returns whether a persistent editor is open for the item at index \a index.
3301
3302 \sa openPersistentEditor(), closePersistentEditor()
3303*/
3304bool QAbstractItemView::isPersistentEditorOpen(const QModelIndex &index) const
3305{
3306 Q_D(const QAbstractItemView);
3307 QWidget *editor = d->editorForIndex(index).widget;
3308 return editor && d->persistent.contains(editor);
3309}
3310
3311/*!
3312 Sets the given \a widget on the item at the given \a index, passing the
3313 ownership of the widget to the viewport.
3314
3315 If \a index is invalid (e.g., if you pass the root index), this function
3316 will do nothing.
3317
3318 The given \a widget's \l{QWidget}{autoFillBackground} property must be set
3319 to true, otherwise the widget's background will be transparent, showing
3320 both the model data and the item at the given \a index.
3321
3322 \note The view takes ownership of the \a widget.
3323 This means if index widget A is replaced with index widget B, index widget A will be
3324 deleted. For example, in the code snippet below, the QLineEdit object will
3325 be deleted.
3326
3327 \snippet code/src_gui_itemviews_qabstractitemview.cpp 1
3328
3329 This function should only be used to display static content within the
3330 visible area corresponding to an item of data. If you want to display
3331 custom dynamic content or implement a custom editor widget, subclass
3332 QStyledItemDelegate instead.
3333
3334 \sa {Delegate Classes}
3335*/
3336void QAbstractItemView::setIndexWidget(const QModelIndex &index, QWidget *widget)
3337{
3338 Q_D(QAbstractItemView);
3339 if (!d->isIndexValid(index))
3340 return;
3341 if (indexWidget(index) == widget)
3342 return;
3343 if (QWidget *oldWidget = indexWidget(index)) {
3344 d->persistent.remove(oldWidget);
3345 d->removeEditor(oldWidget);
3346 oldWidget->removeEventFilter(this);
3347 oldWidget->deleteLater();
3348 }
3349 if (widget) {
3350 widget->setParent(viewport());
3351 d->persistent.insert(widget);
3352 d->addEditor(index, widget, true);
3353 widget->installEventFilter(this);
3354 widget->show();
3355 dataChanged(index, index); // update the geometry
3356 if (!d->delayedPendingLayout) {
3357 widget->setGeometry(visualRect(index));
3358 d->doDelayedItemsLayout(); // relayout due to updated geometry
3359 }
3360 }
3361}
3362
3363/*!
3364 Returns the widget for the item at the given \a index.
3365*/
3366QWidget* QAbstractItemView::indexWidget(const QModelIndex &index) const
3367{
3368 Q_D(const QAbstractItemView);
3369 if (d->isIndexValid(index))
3370 if (QWidget *editor = d->editorForIndex(index).widget.data())
3371 return editor;
3372
3373 return nullptr;
3374}
3375
3376/*!
3377 Scrolls the view to the top.
3378
3379 \sa scrollTo(), scrollToBottom()
3380*/
3381void QAbstractItemView::scrollToTop()
3382{
3383 verticalScrollBar()->setValue(verticalScrollBar()->minimum());
3384}
3385
3386/*!
3387 Scrolls the view to the bottom.
3388
3389 \sa scrollTo(), scrollToTop()
3390*/
3391void QAbstractItemView::scrollToBottom()
3392{
3393 Q_D(QAbstractItemView);
3394 if (d->delayedPendingLayout) {
3395 d->executePostedLayout();
3396 updateGeometries();
3397 }
3398 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
3399}
3400
3401/*!
3402 Updates the area occupied by the given \a index.
3403
3404*/
3405void QAbstractItemView::update(const QModelIndex &index)
3406{
3407 Q_D(QAbstractItemView);
3408 if (index.isValid()) {
3409 const QRect rect = d->visualRect(index);
3410 //this test is important for performance reason
3411 //For example in dataChanged we simply update all the cells without checking
3412 //it can be a major bottleneck to update rects that aren't even part of the viewport
3413 if (d->viewport->rect().intersects(rect))
3414 d->viewport->update(rect);
3415 }
3416}
3417
3418/*!
3419 This slot is called when items with the given \a roles are changed in the
3420 model. The changed items are those from \a topLeft to \a bottomRight
3421 inclusive. If just one item is changed \a topLeft == \a bottomRight.
3422
3423 The \a roles which have been changed can either be an empty container (meaning everything
3424 has changed), or a non-empty container with the subset of roles which have changed.
3425
3426 \note: Qt::ToolTipRole is not honored by dataChanged() in the views provided by Qt.
3427*/
3428void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
3429 const QList<int> &roles)
3430{
3431 Q_UNUSED(roles);
3432 // Single item changed
3433 Q_D(QAbstractItemView);
3434 if (topLeft == bottomRight && topLeft.isValid()) {
3435 const QEditorInfo &editorInfo = d->editorForIndex(topLeft);
3436 //we don't update the edit data if it is static
3437 if (!editorInfo.isStatic && editorInfo.widget) {
3438 QAbstractItemDelegate *delegate = itemDelegateForIndex(topLeft);
3439 if (delegate) {
3440 delegate->setEditorData(editorInfo.widget.data(), topLeft);
3441 }
3442 }
3443 if (isVisible() && !d->delayedPendingLayout) {
3444 // otherwise the items will be updated later anyway
3445 update(topLeft);
3446 }
3447 } else {
3448 d->updateEditorData(topLeft, bottomRight);
3449 if (isVisible() && !d->delayedPendingLayout) {
3450 if (!topLeft.isValid() ||
3451 topLeft.parent() != bottomRight.parent() ||
3452 topLeft.row() > bottomRight.row() ||
3453 topLeft.column() > bottomRight.column()) {
3454 // invalid parameter - call update() to redraw all
3455 qCWarning(lcAIV).nospace()
3456 << "dataChanged() called with an invalid index range:"
3457 << "\n topleft: " << topLeft
3458 << "\n bottomRight:" << bottomRight;
3459 d->viewport->update();
3460 } else if ((bottomRight.row() - topLeft.row() + 1LL) *
3461 (bottomRight.column() - topLeft.column() + 1LL) > d->updateThreshold) {
3462 // too many indices to check - force full update
3463 d->viewport->update();
3464 } else {
3465 const QRect updateRect = d->intersectedRect(d->viewport->rect(), topLeft, bottomRight);
3466 if (!updateRect.isEmpty())
3467 d->viewport->update(updateRect);
3468 }
3469 }
3470 }
3471
3472#if QT_CONFIG(accessibility)
3473 if (QAccessible::isActive()) {
3474 QAccessibleTableModelChangeEvent accessibleEvent(this, QAccessibleTableModelChangeEvent::DataChanged);
3475 accessibleEvent.setFirstRow(topLeft.row());
3476 accessibleEvent.setFirstColumn(topLeft.column());
3477 accessibleEvent.setLastRow(bottomRight.row());
3478 accessibleEvent.setLastColumn(bottomRight.column());
3479 QAccessible::updateAccessibility(&accessibleEvent);
3480
3481 // send accessibility events as needed when current item is modified
3482 if (topLeft.isValid() && topLeft == bottomRight && topLeft == currentIndex())
3483 d->updateItemAccessibility(topLeft, roles);
3484 }
3485#endif
3486 d->updateGeometry();
3487}
3488
3489/*!
3490 This slot is called when rows are inserted. The new rows are those
3491 under the given \a parent from \a start to \a end inclusive. The
3492 base class implementation calls fetchMore() on the model to check
3493 for more data.
3494
3495 \sa rowsAboutToBeRemoved()
3496*/
3497void QAbstractItemView::rowsInserted(const QModelIndex &, int, int)
3498{
3499 if (!isVisible())
3500 d_func()->fetchMoreTimer.start(0, this); //fetch more later
3501 else
3502 updateEditorGeometries();
3503}
3504
3505/*!
3506 This slot is called when rows are about to be removed. The deleted rows are
3507 those under the given \a parent from \a start to \a end inclusive.
3508
3509 \sa rowsInserted()
3510*/
3511void QAbstractItemView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
3512{
3513 Q_D(QAbstractItemView);
3514
3515 setState(CollapsingState);
3516
3517 // Ensure one selected item in single selection mode.
3518 QModelIndex current = currentIndex();
3519 if (d->selectionMode == SingleSelection
3520 && current.isValid()
3521 && current.row() >= start
3522 && current.row() <= end
3523 && current.parent() == parent) {
3524 int totalToRemove = end - start + 1;
3525 if (d->model->rowCount(parent) <= totalToRemove) { // no more children
3526 QModelIndex index = parent;
3527 while (index != d->root && !d->isIndexEnabled(index))
3528 index = index.parent();
3529 if (index != d->root)
3530 setCurrentIndex(index);
3531 } else {
3532 int row = end + 1;
3533 QModelIndex next;
3534 const int rowCount = d->model->rowCount(parent);
3535 bool found = false;
3536 // find the next visible and enabled item
3537 while (row < rowCount && !found) {
3538 next = d->model->index(row++, current.column(), current.parent());
3539#ifdef QT_DEBUG
3540 if (!next.isValid()) {
3541 qCWarning(lcAIV, "Model unexpectedly returned an invalid index");
3542 break;
3543 }
3544#endif
3545 if (!isIndexHidden(next) && d->isIndexEnabled(next)) {
3546 found = true;
3547 break;
3548 }
3549 }
3550
3551 if (!found) {
3552 row = start - 1;
3553 // find the previous visible and enabled item
3554 while (row >= 0) {
3555 next = d->model->index(row--, current.column(), current.parent());
3556#ifdef QT_DEBUG
3557 if (!next.isValid()) {
3558 qCWarning(lcAIV, "Model unexpectedly returned an invalid index");
3559 break;
3560 }
3561#endif
3562 if (!isIndexHidden(next) && d->isIndexEnabled(next))
3563 break;
3564 }
3565 }
3566
3567 setCurrentIndex(next);
3568 }
3569 }
3570
3571 // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
3572 const auto findDirectChildOf = [](const QModelIndex &parent, QModelIndex child)
3573 {
3574 while (child.isValid()) {
3575 const auto parentIndex = child.parent();
3576 if (parentIndex == parent)
3577 return child;
3578 child = parentIndex;
3579 }
3580 return QModelIndex();
3581 };
3582 QEditorIndexHash::iterator i = d->editorIndexHash.begin();
3583 while (i != d->editorIndexHash.end()) {
3584 const QModelIndex index = i.value();
3585 const QModelIndex directChild = findDirectChildOf(parent, index);
3586 if (directChild.isValid() && directChild.row() >= start && directChild.row() <= end) {
3587 QWidget *editor = i.key();
3588 QEditorInfo info = d->indexEditorHash.take(index);
3589 i = d->editorIndexHash.erase(i);
3590 if (info.widget)
3591 d->releaseEditor(editor, index);
3592 } else {
3593 ++i;
3594 }
3595 }
3596}
3597
3598/*!
3599 \internal
3600
3601 This slot is called when rows have been removed. The deleted
3602 rows are those under the given \a parent from \a start to \a end
3603 inclusive.
3604*/
3605void QAbstractItemViewPrivate::rowsRemoved(const QModelIndex &index, int start, int end)
3606{
3607 Q_UNUSED(index);
3608 Q_UNUSED(start);
3609 Q_UNUSED(end);
3610
3611 Q_Q(QAbstractItemView);
3612 if (q->isVisible())
3613 q->updateEditorGeometries();
3614 q->setState(QAbstractItemView::NoState);
3615#if QT_CONFIG(accessibility)
3616 if (QAccessible::isActive()) {
3617 QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::RowsRemoved);
3618 accessibleEvent.setFirstRow(start);
3619 accessibleEvent.setLastRow(end);
3620 QAccessible::updateAccessibility(&accessibleEvent);
3621 }
3622#endif
3623 updateGeometry();
3624}
3625
3626/*!
3627 \internal
3628
3629 This slot is called when columns are about to be removed. The deleted
3630 columns are those under the given \a parent from \a start to \a end
3631 inclusive.
3632*/
3633void QAbstractItemViewPrivate::columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
3634{
3635 Q_Q(QAbstractItemView);
3636
3637 q->setState(QAbstractItemView::CollapsingState);
3638
3639 // Ensure one selected item in single selection mode.
3640 QModelIndex current = q->currentIndex();
3641 if (current.isValid()
3642 && selectionMode == QAbstractItemView::SingleSelection
3643 && current.column() >= start
3644 && current.column() <= end) {
3645 int totalToRemove = end - start + 1;
3646 if (model->columnCount(parent) < totalToRemove) { // no more columns
3647 QModelIndex index = parent;
3648 while (index.isValid() && !isIndexEnabled(index))
3649 index = index.parent();
3650 if (index.isValid())
3651 q->setCurrentIndex(index);
3652 } else {
3653 int column = end;
3654 QModelIndex next;
3655 const int columnCount = model->columnCount(current.parent());
3656 // find the next visible and enabled item
3657 while (column < columnCount) {
3658 next = model->index(current.row(), column++, current.parent());
3659#ifdef QT_DEBUG
3660 if (!next.isValid()) {
3661 qCWarning(lcAIV, "Model unexpectedly returned an invalid index");
3662 break;
3663 }
3664#endif
3665 if (!q->isIndexHidden(next) && isIndexEnabled(next))
3666 break;
3667 }
3668 q->setCurrentIndex(next);
3669 }
3670 }
3671
3672 // Remove all affected editors; this is more efficient than waiting for updateGeometries() to clean out editors for invalid indexes
3673 QEditorIndexHash::iterator it = editorIndexHash.begin();
3674 while (it != editorIndexHash.end()) {
3675 QModelIndex index = it.value();
3676 if (index.column() <= start && index.column() >= end && model->parent(index) == parent) {
3677 QWidget *editor = it.key();
3678 QEditorInfo info = indexEditorHash.take(it.value());
3679 it = editorIndexHash.erase(it);
3680 if (info.widget)
3681 releaseEditor(editor, index);
3682 } else {
3683 ++it;
3684 }
3685 }
3686
3687}
3688
3689/*!
3690 \internal
3691
3692 This slot is called when columns have been removed. The deleted
3693 rows are those under the given \a parent from \a start to \a end
3694 inclusive.
3695*/
3696void QAbstractItemViewPrivate::columnsRemoved(const QModelIndex &index, int start, int end)
3697{
3698 Q_UNUSED(index);
3699 Q_UNUSED(start);
3700 Q_UNUSED(end);
3701
3702 Q_Q(QAbstractItemView);
3703 if (q->isVisible())
3704 q->updateEditorGeometries();
3705 q->setState(QAbstractItemView::NoState);
3706#if QT_CONFIG(accessibility)
3707 if (QAccessible::isActive()) {
3708 QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ColumnsRemoved);
3709 accessibleEvent.setFirstColumn(start);
3710 accessibleEvent.setLastColumn(end);
3711 QAccessible::updateAccessibility(&accessibleEvent);
3712 }
3713#endif
3714 updateGeometry();
3715}
3716
3717
3718/*!
3719 \internal
3720
3721 This slot is called when rows have been inserted.
3722*/
3723void QAbstractItemViewPrivate::rowsInserted(const QModelIndex &index, int start, int end)
3724{
3725 Q_UNUSED(index);
3726 Q_UNUSED(start);
3727 Q_UNUSED(end);
3728
3729#if QT_CONFIG(accessibility)
3730 Q_Q(QAbstractItemView);
3731 if (QAccessible::isActive()) {
3732 QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::RowsInserted);
3733 accessibleEvent.setFirstRow(start);
3734 accessibleEvent.setLastRow(end);
3735 QAccessible::updateAccessibility(&accessibleEvent);
3736 }
3737#endif
3738 updateGeometry();
3739}
3740
3741/*!
3742 \internal
3743
3744 This slot is called when columns have been inserted.
3745*/
3746void QAbstractItemViewPrivate::columnsInserted(const QModelIndex &index, int start, int end)
3747{
3748 Q_UNUSED(index);
3749 Q_UNUSED(start);
3750 Q_UNUSED(end);
3751
3752 Q_Q(QAbstractItemView);
3753 if (q->isVisible())
3754 q->updateEditorGeometries();
3755#if QT_CONFIG(accessibility)
3756 if (QAccessible::isActive()) {
3757 QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ColumnsInserted);
3758 accessibleEvent.setFirstColumn(start);
3759 accessibleEvent.setLastColumn(end);
3760 QAccessible::updateAccessibility(&accessibleEvent);
3761 }
3762#endif
3763 updateGeometry();
3764}
3765
3766/*!
3767 \internal
3768*/
3769void QAbstractItemViewPrivate::modelDestroyed()
3770{
3771 model = QAbstractItemModelPrivate::staticEmptyModel();
3772 doDelayedReset();
3773}
3774
3775/*!
3776 \internal
3777
3778 This slot is called when the layout is changed.
3779*/
3780void QAbstractItemViewPrivate::layoutChanged()
3781{
3782 doDelayedItemsLayout();
3783#if QT_CONFIG(accessibility)
3784 Q_Q(QAbstractItemView);
3785 if (QAccessible::isActive()) {
3786 QAccessibleTableModelChangeEvent accessibleEvent(q, QAccessibleTableModelChangeEvent::ModelReset);
3787 QAccessible::updateAccessibility(&accessibleEvent);
3788 }
3789#endif
3790}
3791
3792void QAbstractItemViewPrivate::rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
3793{
3794 layoutChanged();
3795}
3796
3797void QAbstractItemViewPrivate::columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)
3798{
3799 layoutChanged();
3800}
3801
3802QRect QAbstractItemViewPrivate::intersectedRect(const QRect rect, const QModelIndex &topLeft, const QModelIndex &bottomRight) const
3803{
3804 Q_Q(const QAbstractItemView);
3805
3806 const auto parentIdx = topLeft.parent();
3807 QRect updateRect;
3808 for (int r = topLeft.row(); r <= bottomRight.row(); ++r) {
3809 for (int c = topLeft.column(); c <= bottomRight.column(); ++c)
3810 updateRect |= q->visualRect(model->index(r, c, parentIdx));
3811 }
3812 return rect.intersected(updateRect);
3813}
3814
3815/*!
3816 This slot is called when the selection is changed. The previous
3817 selection (which may be empty), is specified by \a deselected, and the
3818 new selection by \a selected.
3819
3820 \sa setSelection()
3821*/
3822void QAbstractItemView::selectionChanged(const QItemSelection &selected,
3823 const QItemSelection &deselected)
3824{
3825 Q_D(QAbstractItemView);
3826 if (isVisible() && updatesEnabled()) {
3827 d->viewport->update(visualRegionForSelection(deselected) | visualRegionForSelection(selected));
3828 }
3829}
3830
3831/*!
3832 This slot is called when a new item becomes the current item.
3833 The previous current item is specified by the \a previous index, and the new
3834 item by the \a current index.
3835
3836 If you want to know about changes to items see the
3837 dataChanged() signal.
3838*/
3839void QAbstractItemView::currentChanged(const QModelIndex &current, const QModelIndex &previous)
3840{
3841 Q_D(QAbstractItemView);
3842 Q_ASSERT(d->model);
3843
3844 QPersistentModelIndex persistentCurrent(current); // in case commitData() moves things around (QTBUG-127852)
3845
3846 if (previous.isValid()) {
3847 QModelIndex buddy = d->model->buddy(previous);
3848 QWidget *editor = d->editorForIndex(buddy).widget.data();
3849 if (isVisible()) {
3850 update(previous);
3851 }
3852 if (editor && !d->persistent.contains(editor)) {
3853 const bool rowChanged = current.row() != previous.row();
3854 commitData(editor); // might invalidate previous, don't use after this line (QTBUG-127852)
3855 if (rowChanged)
3856 closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
3857 else
3858 closeEditor(editor, QAbstractItemDelegate::NoHint);
3859 }
3860 }
3861
3862 const QModelIndex newCurrent = persistentCurrent;
3863
3864 QItemSelectionModel::SelectionFlags command = selectionCommand(newCurrent, nullptr);
3865 if ((command & QItemSelectionModel::Current) == 0)
3866 d->currentSelectionStartIndex = newCurrent;
3867
3868 if (newCurrent.isValid() && !d->autoScrollTimer.isActive()) {
3869 if (isVisible()) {
3870 if (d->autoScroll)
3871 scrollTo(newCurrent);
3872 update(newCurrent);
3873 edit(newCurrent, CurrentChanged, nullptr);
3874 if (newCurrent.row() == (d->model->rowCount(d->root) - 1))
3875 d->fetchMore();
3876 } else {
3877 d->shouldScrollToCurrentOnShow = d->autoScroll;
3878 }
3879 }
3880 setAttribute(Qt::WA_InputMethodEnabled, (newCurrent.isValid() && (newCurrent.flags() & Qt::ItemIsEditable)));
3881}
3882
3883#if QT_CONFIG(draganddrop)
3884/*!
3885 Starts a drag by calling drag->exec() using the given \a supportedActions.
3886*/
3887void QAbstractItemView::startDrag(Qt::DropActions supportedActions)
3888{
3889 Q_D(QAbstractItemView);
3890 QModelIndexList indexes = d->selectedDraggableIndexes();
3891 if (indexes.size() > 0) {
3892 QMimeData *data = d->model->mimeData(indexes);
3893 if (!data)
3894 return;
3895 QRect rect;
3896 QPixmap pixmap = d->renderToPixmap(indexes, &rect);
3897 rect.adjust(horizontalOffset(), verticalOffset(), 0, 0);
3898 QDrag *drag = new QDrag(this);
3899 drag->setPixmap(pixmap);
3900 drag->setMimeData(data);
3901 drag->setHotSpot(d->pressedPosition - rect.topLeft());
3902 Qt::DropAction defaultDropAction = Qt::IgnoreAction;
3903 if (dragDropMode() == InternalMove)
3904 supportedActions &= ~Qt::CopyAction;
3905 if (d->defaultDropAction != Qt::IgnoreAction && (supportedActions & d->defaultDropAction))
3906 defaultDropAction = d->defaultDropAction;
3907 else if (supportedActions & Qt::CopyAction && dragDropMode() != QAbstractItemView::InternalMove)
3908 defaultDropAction = Qt::CopyAction;
3909 d->dropEventMoved = false;
3910 if (drag->exec(supportedActions, defaultDropAction) == Qt::MoveAction && !d->dropEventMoved) {
3911 if (dragDropMode() != InternalMove || drag->target() == viewport())
3912 d->clearOrRemove();
3913 }
3914 d->dropEventMoved = false;
3915 // Reset the drop indicator
3916 d->dropIndicatorRect = QRect();
3917 d->dropIndicatorPosition = OnItem;
3918 }
3919}
3920#endif // QT_CONFIG(draganddrop)
3921
3922/*!
3923 \since 6.0
3924
3925 Initialize the \a option structure with the view's palette, font, state,
3926 alignments etc.
3927
3928 \note Implementations of this methods should check the \l{QStyleOption::}{version}
3929 of the structure received, populate all members the implementation is familiar with,
3930 and set the version member to the one supported by the implementation before returning.
3931*/
3932void QAbstractItemView::initViewItemOption(QStyleOptionViewItem *option) const
3933{
3934 Q_D(const QAbstractItemView);
3935 option->initFrom(this);
3936 option->state &= ~QStyle::State_MouseOver;
3937 option->font = font();
3938
3939 // On mac the focus appearance follows window activation
3940 // not widget activation
3941 if (!hasFocus())
3942 option->state &= ~QStyle::State_Active;
3943
3944 option->state &= ~QStyle::State_HasFocus;
3945 if (d->iconSize.isValid()) {
3946 option->decorationSize = d->iconSize;
3947 } else {
3948 int pm = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this);
3949 option->decorationSize = QSize(pm, pm);
3950 }
3951 option->decorationPosition = QStyleOptionViewItem::Left;
3952 option->decorationAlignment = Qt::AlignCenter;
3953 option->displayAlignment = Qt::AlignLeft|Qt::AlignVCenter;
3954 option->textElideMode = d->textElideMode;
3955 option->rect = QRect();
3956 option->showDecorationSelected = style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, nullptr, this);
3957 if (d->wrapItemText)
3958 option->features = QStyleOptionViewItem::WrapText;
3959 option->locale = locale();
3960 option->locale.setNumberOptions(QLocale::OmitGroupSeparator);
3961 option->widget = this;
3962}
3963
3964/*!
3965 Returns the item view's state.
3966
3967 \sa setState()
3968*/
3969QAbstractItemView::State QAbstractItemView::state() const
3970{
3971 Q_D(const QAbstractItemView);
3972 return d->state;
3973}
3974
3975/*!
3976 Sets the item view's state to the given \a state.
3977
3978 \sa state()
3979*/
3980void QAbstractItemView::setState(State state)
3981{
3982 Q_D(QAbstractItemView);
3983 d->state = state;
3984}
3985
3986/*!
3987 Schedules a layout of the items in the view to be executed when the
3988 event processing starts.
3989
3990 Even if scheduleDelayedItemsLayout() is called multiple times before
3991 events are processed, the view will only do the layout once.
3992
3993 \sa executeDelayedItemsLayout()
3994*/
3995void QAbstractItemView::scheduleDelayedItemsLayout()
3996{
3997 Q_D(QAbstractItemView);
3998 d->doDelayedItemsLayout();
3999}
4000
4001/*!
4002 Executes the scheduled layouts without waiting for the event processing
4003 to begin.
4004
4005 \sa scheduleDelayedItemsLayout()
4006*/
4007void QAbstractItemView::executeDelayedItemsLayout()
4008{
4009 Q_D(QAbstractItemView);
4010 d->executePostedLayout();
4011}
4012
4013/*!
4014 Marks the given \a region as dirty and schedules it to be updated.
4015 You only need to call this function if you are implementing
4016 your own view subclass.
4017
4018 \sa scrollDirtyRegion(), dirtyRegionOffset()
4019*/
4020
4021void QAbstractItemView::setDirtyRegion(const QRegion &region)
4022{
4023 Q_D(QAbstractItemView);
4024 d->setDirtyRegion(region);
4025}
4026
4027/*!
4028 Prepares the view for scrolling by (\a{dx},\a{dy}) pixels by moving the dirty regions in the
4029 opposite direction. You only need to call this function if you are implementing a scrolling
4030 viewport in your view subclass.
4031
4032 If you implement scrollContentsBy() in a subclass of QAbstractItemView, call this function
4033 before you call QWidget::scroll() on the viewport. Alternatively, just call update().
4034
4035 \sa scrollContentsBy(), dirtyRegionOffset(), setDirtyRegion()
4036*/
4037void QAbstractItemView::scrollDirtyRegion(int dx, int dy)
4038{
4039 Q_D(QAbstractItemView);
4040 d->scrollDirtyRegion(dx, dy);
4041}
4042
4043/*!
4044 Returns the offset of the dirty regions in the view.
4045
4046 If you use scrollDirtyRegion() and implement a paintEvent() in a subclass of
4047 QAbstractItemView, you should translate the area given by the paint event with
4048 the offset returned from this function.
4049
4050 \sa scrollDirtyRegion(), setDirtyRegion()
4051*/
4052QPoint QAbstractItemView::dirtyRegionOffset() const
4053{
4054 Q_D(const QAbstractItemView);
4055 return d->scrollDelayOffset;
4056}
4057
4058/*!
4059 \internal
4060*/
4061void QAbstractItemView::startAutoScroll()
4062{
4063 d_func()->startAutoScroll();
4064}
4065
4066/*!
4067 \internal
4068*/
4069void QAbstractItemView::stopAutoScroll()
4070{
4071 d_func()->stopAutoScroll();
4072}
4073
4074/*!
4075 \internal
4076*/
4077void QAbstractItemView::doAutoScroll()
4078{
4079 // find how much we should scroll with
4080 Q_D(QAbstractItemView);
4081 QScrollBar *verticalScroll = verticalScrollBar();
4082 QScrollBar *horizontalScroll = horizontalScrollBar();
4083
4084 // QHeaderView does not (normally) have scrollbars
4085 // It needs to use its parents scroll instead
4086 QHeaderView *hv = qobject_cast<QHeaderView*>(this);
4087 if (hv) {
4088 QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea*>(parentWidget());
4089 if (parent) {
4090 if (hv->orientation() == Qt::Horizontal) {
4091 if (!hv->horizontalScrollBar() || !hv->horizontalScrollBar()->isVisible())
4092 horizontalScroll = parent->horizontalScrollBar();
4093 } else {
4094 if (!hv->verticalScrollBar() || !hv->verticalScrollBar()->isVisible())
4095 verticalScroll = parent->verticalScrollBar();
4096 }
4097 }
4098 }
4099
4100 const int verticalStep = verticalScroll->pageStep();
4101 const int horizontalStep = horizontalScroll->pageStep();
4102 if (d->autoScrollCount < qMax(verticalStep, horizontalStep))
4103 ++d->autoScrollCount;
4104
4105 const int margin = d->autoScrollMargin;
4106 const int verticalValue = verticalScroll->value();
4107 const int horizontalValue = horizontalScroll->value();
4108
4109 const QPoint pos = d->draggedPosition - d->offset();
4110 const QRect area = QWidgetPrivate::get(d->viewport)->clipRect();
4111
4112 // do the scrolling if we are in the scroll margins
4113 if (pos.y() - area.top() < margin)
4114 verticalScroll->setValue(verticalValue - d->autoScrollCount);
4115 else if (area.bottom() - pos.y() < margin)
4116 verticalScroll->setValue(verticalValue + d->autoScrollCount);
4117 if (pos.x() - area.left() < margin)
4118 horizontalScroll->setValue(horizontalValue - d->autoScrollCount);
4119 else if (area.right() - pos.x() < margin)
4120 horizontalScroll->setValue(horizontalValue + d->autoScrollCount);
4121 // if nothing changed, stop scrolling
4122 const bool verticalUnchanged = (verticalValue == verticalScroll->value());
4123 const bool horizontalUnchanged = (horizontalValue == horizontalScroll->value());
4124 if (verticalUnchanged && horizontalUnchanged) {
4125 stopAutoScroll();
4126 } else {
4127#if QT_CONFIG(draganddrop)
4128 d->dropIndicatorRect = QRect();
4129 d->dropIndicatorPosition = QAbstractItemView::OnViewport;
4130#endif
4131 switch (state()) {
4132 case QAbstractItemView::DragSelectingState: {
4133 // mouseMoveEvent updates the drag-selection rectangle, so fake an event. This also
4134 // updates draggedPosition taking the now scrolled viewport into account.
4135 const QPoint globalPos = d->viewport->mapToGlobal(pos);
4136 const QPoint windowPos = window()->mapFromGlobal(globalPos);
4137 QMouseEvent mm(QEvent::MouseMove, pos, windowPos, globalPos,
4138 Qt::NoButton, Qt::LeftButton, d->pressedModifiers,
4139 Qt::MouseEventSynthesizedByQt);
4140 QApplication::sendEvent(viewport(), &mm);
4141 break;
4142 }
4143 case QAbstractItemView::DraggingState: {
4144 // we can't simulate mouse (it would throw off the drag'n'drop state logic) or drag
4145 // (we don't have the mime data or the actions) move events during drag'n'drop, so
4146 // update our dragged position manually after the scroll. "pos" is the old
4147 // draggedPosition - d->offset(), and d->offset() is now updated after scrolling, so
4148 // pos + d->offset() gives us the new position.
4149 d->draggedPosition = pos + d->offset();
4150 break;
4151 }
4152 default:
4153 break;
4154 }
4155 d->viewport->update();
4156 }
4157}
4158
4159/*!
4160 Returns the SelectionFlags to be used when updating a selection model
4161 for the specified \a index. The result depends on the current
4162 selectionMode(), and on the user input event \a event, which can be
4163 \nullptr.
4164
4165 Reimplement this function to define your own selection behavior.
4166
4167 \sa setSelection()
4168*/
4169QItemSelectionModel::SelectionFlags QAbstractItemView::selectionCommand(const QModelIndex &index,
4170 const QEvent *event) const
4171{
4172 Q_D(const QAbstractItemView);
4173 Qt::KeyboardModifiers keyModifiers = event && event->isInputEvent()
4174 ? static_cast<const QInputEvent*>(event)->modifiers()
4175 : Qt::NoModifier;
4176 switch (d->selectionMode) {
4177 case NoSelection: // Never update selection model
4178 return QItemSelectionModel::NoUpdate;
4179 case SingleSelection: // ClearAndSelect on valid index otherwise NoUpdate
4180 if (event) {
4181 switch (event->type()) {
4182 case QEvent::MouseButtonPress:
4183 // press with any modifiers on a selected item does nothing
4184 if (d->pressedAlreadySelected)
4185 return QItemSelectionModel::NoUpdate;
4186 break;
4187 case QEvent::MouseButtonRelease:
4188 // clicking into area with no items does nothing
4189 if (!index.isValid())
4190 return QItemSelectionModel::NoUpdate;
4191 Q_FALLTHROUGH();
4192 case QEvent::KeyPress:
4193 // ctrl-release on selected item deselects
4194 if ((keyModifiers & Qt::ControlModifier) && d->selectionModel->isSelected(index))
4195 return QItemSelectionModel::Deselect | d->selectionBehaviorFlags();
4196 break;
4197 default:
4198 break;
4199 }
4200 }
4201 return QItemSelectionModel::ClearAndSelect | d->selectionBehaviorFlags();
4202 case MultiSelection:
4203 return d->multiSelectionCommand(index, event);
4204 case ExtendedSelection:
4205 return d->extendedSelectionCommand(index, event);
4206 case ContiguousSelection:
4207 return d->contiguousSelectionCommand(index, event);
4208 }
4209 return QItemSelectionModel::NoUpdate;
4210}
4211
4212QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::multiSelectionCommand(
4213 const QModelIndex &index, const QEvent *event) const
4214{
4215 Q_UNUSED(index);
4216
4217 if (event) {
4218 switch (event->type()) {
4219 case QEvent::KeyPress:
4220 if (static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Space
4221 || static_cast<const QKeyEvent*>(event)->key() == Qt::Key_Select)
4222 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4223 break;
4224 case QEvent::MouseButtonPress:
4225 if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
4226 // since the press might start a drag, deselect only on release
4227 if (!pressedAlreadySelected
4228#if QT_CONFIG(draganddrop)
4229 || !dragEnabled || !isIndexDragEnabled(index)
4230#endif
4231 )
4232 return QItemSelectionModel::Toggle|selectionBehaviorFlags(); // toggle
4233 }
4234 break;
4235 case QEvent::MouseButtonRelease:
4236 if (static_cast<const QMouseEvent*>(event)->button() == Qt::LeftButton) {
4237 if (pressedAlreadySelected
4238#if QT_CONFIG(draganddrop)
4239 && dragEnabled && isIndexDragEnabled(index)
4240#endif
4241 && index == pressedIndex)
4242 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4243 return QItemSelectionModel::NoUpdate|selectionBehaviorFlags(); // finalize
4244 }
4245 break;
4246 case QEvent::MouseMove:
4247 if (static_cast<const QMouseEvent*>(event)->buttons() & Qt::LeftButton)
4248 return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags(); // toggle drag select
4249 break;
4250 default:
4251 break;
4252 }
4253 return QItemSelectionModel::NoUpdate;
4254 }
4255
4256 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4257}
4258
4259QItemSelectionModel::SelectionFlags QAbstractItemViewPrivate::extendedSelectionCommand(
4260 const QModelIndex &index, const QEvent *event) const
4261{
4262 Qt::KeyboardModifiers modifiers = event && event->isInputEvent()
4263 ? static_cast<const QInputEvent*>(event)->modifiers()
4264 : QGuiApplication::keyboardModifiers();
4265 if (event) {
4266 switch (event->type()) {
4267 case QEvent::MouseMove: {
4268 // Toggle on MouseMove
4269 if (modifiers & Qt::ControlModifier)
4270 return QItemSelectionModel::ToggleCurrent|selectionBehaviorFlags();
4271 break;
4272 }
4273 case QEvent::MouseButtonPress: {
4274 const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
4275 const bool rightButtonPressed = button & Qt::RightButton;
4276 const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
4277 const bool controlKeyPressed = modifiers & Qt::ControlModifier;
4278 const bool indexIsSelected = selectionModel->isSelected(index);
4279 if ((shiftKeyPressed || controlKeyPressed) && rightButtonPressed)
4280 return QItemSelectionModel::NoUpdate;
4281 if (!shiftKeyPressed && !controlKeyPressed && indexIsSelected)
4282 return QItemSelectionModel::NoUpdate;
4283 if (!index.isValid() && !rightButtonPressed && !shiftKeyPressed && !controlKeyPressed)
4284 return QItemSelectionModel::Clear;
4285 if (!index.isValid())
4286 return QItemSelectionModel::NoUpdate;
4287 // since the press might start a drag, deselect only on release
4288 if (controlKeyPressed && !rightButtonPressed && pressedAlreadySelected
4289#if QT_CONFIG(draganddrop)
4290 && dragEnabled && isIndexDragEnabled(index)
4291#endif
4292 ) {
4293 return QItemSelectionModel::NoUpdate;
4294 }
4295 break;
4296 }
4297 case QEvent::MouseButtonRelease: {
4298 // ClearAndSelect on MouseButtonRelease if MouseButtonPress on selected item or empty area
4299 const Qt::MouseButton button = static_cast<const QMouseEvent*>(event)->button();
4300 const bool rightButtonPressed = button & Qt::RightButton;
4301 const bool shiftKeyPressed = modifiers & Qt::ShiftModifier;
4302 const bool controlKeyPressed = modifiers & Qt::ControlModifier;
4303 if (((index == pressedIndex && selectionModel->isSelected(index))
4304 || !index.isValid()) && state != QAbstractItemView::DragSelectingState
4305 && !shiftKeyPressed && !controlKeyPressed && (!rightButtonPressed || !index.isValid()))
4306 return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
4307 if (index == pressedIndex && controlKeyPressed && !rightButtonPressed
4308#if QT_CONFIG(draganddrop)
4309 && dragEnabled && isIndexDragEnabled(index)
4310#endif
4311 ) {
4312 break;
4313 }
4314 return QItemSelectionModel::NoUpdate;
4315 }
4316 case QEvent::KeyPress: {
4317 // NoUpdate on Key movement and Ctrl
4318 switch (static_cast<const QKeyEvent*>(event)->key()) {
4319 case Qt::Key_Backtab:
4320 modifiers = modifiers & ~Qt::ShiftModifier; // special case for backtab
4321 Q_FALLTHROUGH();
4322 case Qt::Key_Down:
4323 case Qt::Key_Up:
4324 case Qt::Key_Left:
4325 case Qt::Key_Right:
4326 case Qt::Key_Home:
4327 case Qt::Key_End:
4328 case Qt::Key_PageUp:
4329 case Qt::Key_PageDown:
4330 case Qt::Key_Tab:
4331 if (modifiers & Qt::ControlModifier)
4332 return QItemSelectionModel::NoUpdate;
4333 break;
4334 case Qt::Key_Select:
4335 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4336 case Qt::Key_Space:// Toggle on Ctrl-Qt::Key_Space, Select on Space
4337 if (modifiers & Qt::ControlModifier)
4338 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4339 return QItemSelectionModel::Select|selectionBehaviorFlags();
4340 default:
4341 break;
4342 }
4343 break;
4344 }
4345 default:
4346 break;
4347 }
4348 }
4349
4350 if (modifiers & Qt::ShiftModifier)
4351 return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
4352 if (modifiers & Qt::ControlModifier)
4353 return QItemSelectionModel::Toggle|selectionBehaviorFlags();
4354 if (state == QAbstractItemView::DragSelectingState) {
4355 //when drag-selecting we need to clear any previous selection and select the current one
4356 return QItemSelectionModel::Clear|QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
4357 }
4358
4359 return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
4360}
4361
4362QItemSelectionModel::SelectionFlags
4363QAbstractItemViewPrivate::contiguousSelectionCommand(const QModelIndex &index,
4364 const QEvent *event) const
4365{
4366 QItemSelectionModel::SelectionFlags flags = extendedSelectionCommand(index, event);
4367 const int Mask = QItemSelectionModel::Clear | QItemSelectionModel::Select
4368 | QItemSelectionModel::Deselect | QItemSelectionModel::Toggle
4369 | QItemSelectionModel::Current;
4370
4371 switch (flags & Mask) {
4372 case QItemSelectionModel::Clear:
4373 case QItemSelectionModel::ClearAndSelect:
4374 case QItemSelectionModel::SelectCurrent:
4375 return flags;
4376 case QItemSelectionModel::NoUpdate:
4377 if (event &&
4378 (event->type() == QEvent::MouseButtonPress
4379 || event->type() == QEvent::MouseButtonRelease))
4380 return flags;
4381 return QItemSelectionModel::ClearAndSelect|selectionBehaviorFlags();
4382 default:
4383 return QItemSelectionModel::SelectCurrent|selectionBehaviorFlags();
4384 }
4385}
4386
4387void QAbstractItemViewPrivate::fetchMore()
4388{
4389 fetchMoreTimer.stop();
4390 if (!model->canFetchMore(root))
4391 return;
4392 int last = model->rowCount(root) - 1;
4393 if (last < 0) {
4394 model->fetchMore(root);
4395 return;
4396 }
4397
4398 QModelIndex index = model->index(last, 0, root);
4399 QRect rect = q_func()->visualRect(index);
4400 if (viewport->rect().intersects(rect))
4401 model->fetchMore(root);
4402}
4403
4404bool QAbstractItemViewPrivate::shouldEdit(QAbstractItemView::EditTrigger trigger,
4405 const QModelIndex &index) const
4406{
4407 if (!index.isValid())
4408 return false;
4409 Qt::ItemFlags flags = model->flags(index);
4410 if (((flags & Qt::ItemIsEditable) == 0) || ((flags & Qt::ItemIsEnabled) == 0))
4411 return false;
4412 if (state == QAbstractItemView::EditingState)
4413 return false;
4414 if (hasEditor(index))
4415 return false;
4416 if (trigger == QAbstractItemView::AllEditTriggers) // force editing
4417 return true;
4418 if ((trigger & editTriggers) == QAbstractItemView::SelectedClicked
4419 && !selectionModel->isSelected(index))
4420 return false;
4421 return (trigger & editTriggers);
4422}
4423
4424bool QAbstractItemViewPrivate::shouldForwardEvent(QAbstractItemView::EditTrigger trigger,
4425 const QEvent *event) const
4426{
4427 if (!event || (trigger & editTriggers) != QAbstractItemView::AnyKeyPressed)
4428 return false;
4429
4430 switch (event->type()) {
4431 case QEvent::KeyPress:
4432 case QEvent::MouseButtonDblClick:
4433 case QEvent::MouseButtonPress:
4434 case QEvent::MouseButtonRelease:
4435 case QEvent::MouseMove:
4436 return true;
4437 default:
4438 break;
4439 };
4440
4441 return false;
4442}
4443
4444bool QAbstractItemViewPrivate::shouldAutoScroll(const QPoint &pos) const
4445{
4446 if (!autoScroll)
4447 return false;
4448 const QRect area = QWidgetPrivate::get(viewport)->clipRect();
4449 return (pos.y() - area.top() < autoScrollMargin)
4450 || (area.bottom() - pos.y() < autoScrollMargin)
4451 || (pos.x() - area.left() < autoScrollMargin)
4452 || (area.right() - pos.x() < autoScrollMargin);
4453}
4454
4455void QAbstractItemViewPrivate::doDelayedItemsLayout(int delay)
4456{
4457 if (!delayedPendingLayout) {
4458 delayedPendingLayout = true;
4459 delayedLayout.start(delay, q_func());
4460 }
4461}
4462
4463void QAbstractItemViewPrivate::interruptDelayedItemsLayout() const
4464{
4465 delayedLayout.stop();
4466 delayedPendingLayout = false;
4467}
4468
4469void QAbstractItemViewPrivate::updateGeometry()
4470{
4471 Q_Q(QAbstractItemView);
4472 if (sizeAdjustPolicy == QAbstractScrollArea::AdjustIgnored)
4473 return;
4474 if (sizeAdjustPolicy == QAbstractScrollArea::AdjustToContents || !shownOnce)
4475 q->updateGeometry();
4476}
4477
4478/*
4479 Handles selection of content for some editors containing QLineEdit.
4480
4481 ### Qt 7 This should be done by a virtual method in QAbstractItemDelegate.
4482*/
4483void QAbstractItemViewPrivate::selectAllInEditor(QWidget *editor)
4484{
4485 while (QWidget *fp = editor->focusProxy())
4486 editor = fp;
4487
4488#if QT_CONFIG(lineedit)
4489 if (QLineEdit *le = qobject_cast<QLineEdit*>(editor))
4490 le->selectAll();
4491#endif
4492#if QT_CONFIG(spinbox)
4493 if (QSpinBox *sb = qobject_cast<QSpinBox*>(editor))
4494 sb->selectAll();
4495 else if (QDoubleSpinBox *dsb = qobject_cast<QDoubleSpinBox*>(editor))
4496 dsb->selectAll();
4497#endif
4498}
4499
4500QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
4501 const QStyleOptionViewItem &options)
4502{
4503 Q_Q(QAbstractItemView);
4504 QWidget *w = editorForIndex(index).widget.data();
4505 if (!w) {
4506 QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
4507 if (!delegate)
4508 return nullptr;
4509 w = delegate->createEditor(viewport, options, index);
4510 if (w) {
4511 w->installEventFilter(delegate);
4512 QObject::connect(w, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
4513 delegate->updateEditorGeometry(w, options, index);
4514 delegate->setEditorData(w, index);
4515 addEditor(index, w, false);
4516 if (w->parent() == viewport)
4517 QWidget::setTabOrder(q, w);
4518
4519 selectAllInEditor(w);
4520 }
4521 }
4522
4523 return w;
4524}
4525
4526void QAbstractItemViewPrivate::updateEditorData(const QModelIndex &tl, const QModelIndex &br)
4527{
4528 Q_Q(QAbstractItemView);
4529 // we are counting on having relatively few editors
4530 const bool checkIndexes = tl.isValid() && br.isValid();
4531 const QModelIndex parent = tl.parent();
4532 // QTBUG-25370: We need to copy the indexEditorHash, because while we're
4533 // iterating over it, we are calling methods which can allow user code to
4534 // call a method on *this which can modify the member indexEditorHash.
4535 const QIndexEditorHash indexEditorHashCopy = indexEditorHash;
4536 QIndexEditorHash::const_iterator it = indexEditorHashCopy.constBegin();
4537 for (; it != indexEditorHashCopy.constEnd(); ++it) {
4538 QWidget *editor = it.value().widget.data();
4539 const QModelIndex index = it.key();
4540 if (it.value().isStatic || !editor || !index.isValid() ||
4541 (checkIndexes
4542 && (index.row() < tl.row() || index.row() > br.row()
4543 || index.column() < tl.column() || index.column() > br.column()
4544 || index.parent() != parent)))
4545 continue;
4546
4547 QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
4548 if (delegate) {
4549 delegate->setEditorData(editor, index);
4550 }
4551 }
4552}
4553
4554/*!
4555 \internal
4556
4557 In DND if something has been moved then this is called.
4558 Typically this means you should "remove" the selected item or row,
4559 but the behavior is view-dependent (table just clears the selected indexes for example).
4560
4561 Either remove the selected rows or clear them
4562*/
4563void QAbstractItemViewPrivate::clearOrRemove()
4564{
4565#if QT_CONFIG(draganddrop)
4566 const QItemSelection selection = selectionModel->selection();
4567
4568 if (!overwrite) {
4569 for (const auto &selected : selection) {
4570 if (selected.left() != 0)
4571 continue;
4572 const QModelIndex parent = selected.parent();
4573 if (selected.right() != (model->columnCount(parent) - 1))
4574 continue;
4575 int count = selected.bottom() - selected.top() + 1;
4576 model->removeRows(selected.top(), count, parent);
4577 }
4578 } else {
4579 // we can't remove the rows so reset the items (i.e. the view is like a table)
4580 const QModelIndexList selectedIndexes = selection.indexes();
4581 for (const auto &index : selectedIndexes) {
4582 QMap<int, QVariant> roles = model->itemData(index);
4583 for (auto &val : roles)
4584 val = QVariant();
4585 model->setItemData(index, roles);
4586 }
4587 }
4588#endif
4589}
4590
4591/*!
4592 \internal
4593
4594 When persistent aeditor gets/loses focus, we need to check
4595 and setcorrectly the current index.
4596*/
4597void QAbstractItemViewPrivate::checkPersistentEditorFocus()
4598{
4599 Q_Q(QAbstractItemView);
4600 if (QWidget *widget = QApplication::focusWidget()) {
4601 if (persistent.contains(widget)) {
4602 //a persistent editor has gained the focus
4603 QModelIndex index = indexForEditor(widget);
4604 if (selectionModel->currentIndex() != index)
4605 q->setCurrentIndex(index);
4606 }
4607 }
4608}
4609
4610
4611const QEditorInfo & QAbstractItemViewPrivate::editorForIndex(const QModelIndex &index) const
4612{
4613 static QEditorInfo nullInfo;
4614
4615 // do not try to search to avoid slow implicit cast from QModelIndex to QPersistentModelIndex
4616 if (indexEditorHash.isEmpty())
4617 return nullInfo;
4618
4619 QIndexEditorHash::const_iterator it = indexEditorHash.find(index);
4620 if (it == indexEditorHash.end())
4621 return nullInfo;
4622
4623 return it.value();
4624}
4625
4626bool QAbstractItemViewPrivate::hasEditor(const QModelIndex &index) const
4627{
4628 // Search's implicit cast (QModelIndex to QPersistentModelIndex) is slow; use cheap pre-test to avoid when we can.
4629 return !indexEditorHash.isEmpty() && indexEditorHash.contains(index);
4630}
4631
4632QModelIndex QAbstractItemViewPrivate::indexForEditor(QWidget *editor) const
4633{
4634 // do not try to search to avoid slow implicit cast from QModelIndex to QPersistentModelIndex
4635 if (indexEditorHash.isEmpty())
4636 return QModelIndex();
4637
4638 QEditorIndexHash::const_iterator it = editorIndexHash.find(editor);
4639 if (it == editorIndexHash.end())
4640 return QModelIndex();
4641
4642 return it.value();
4643}
4644
4645void QAbstractItemViewPrivate::removeEditor(QWidget *editor)
4646{
4647 Q_Q(QAbstractItemView);
4648 if (editor)
4649 QObject::disconnect(editor, &QWidget::destroyed, q, &QAbstractItemView::editorDestroyed);
4650 const auto it = editorIndexHash.constFind(editor);
4651 if (it != editorIndexHash.cend()) {
4652 indexEditorHash.remove(it.value());
4653 editorIndexHash.erase(it);
4654 }
4655}
4656
4657void QAbstractItemViewPrivate::addEditor(const QModelIndex &index, QWidget *editor, bool isStatic)
4658{
4659 editorIndexHash.insert(editor, index);
4660 indexEditorHash.insert(index, QEditorInfo(editor, isStatic));
4661}
4662
4663bool QAbstractItemViewPrivate::sendDelegateEvent(const QModelIndex &index, QEvent *event) const
4664{
4665 Q_Q(const QAbstractItemView);
4666 QModelIndex buddy = model->buddy(index);
4667 QStyleOptionViewItem options;
4668 q->initViewItemOption(&options);
4669 options.rect = q->visualRect(buddy);
4670 options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
4671 QAbstractItemDelegate *delegate = q->itemDelegateForIndex(index);
4672 return (event && delegate && delegate->editorEvent(event, model, options, buddy));
4673}
4674
4675bool QAbstractItemViewPrivate::openEditor(const QModelIndex &index, QEvent *event)
4676{
4677 Q_Q(QAbstractItemView);
4678
4679 QModelIndex buddy = model->buddy(index);
4680 QStyleOptionViewItem options;
4681 q->initViewItemOption(&options);
4682 options.rect = q->visualRect(buddy);
4683 options.state |= (buddy == q->currentIndex() ? QStyle::State_HasFocus : QStyle::State_None);
4684
4685 QWidget *w = editor(buddy, options);
4686 if (!w)
4687 return false;
4688
4689 q->setState(QAbstractItemView::EditingState);
4690 w->show();
4691 if (!waitForIMCommit)
4692 w->setFocus();
4693 else
4694 q->updateMicroFocus();
4695
4696 if (event)
4697 QCoreApplication::sendEvent(w->focusProxy() ? w->focusProxy() : w, event);
4698
4699 return true;
4700}
4701
4702/*
4703 \internal
4704
4705 returns the pair QRect/QModelIndex that should be painted on the viewports's rect
4706*/
4707
4708QItemViewPaintPairs QAbstractItemViewPrivate::draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const
4709{
4710 Q_ASSERT(r);
4711 Q_Q(const QAbstractItemView);
4712 QRect &rect = *r;
4713 const QRect viewportRect = viewport->rect();
4714 QItemViewPaintPairs ret;
4715 for (const auto &index : indexes) {
4716 const QRect current = q->visualRect(index);
4717 if (current.intersects(viewportRect)) {
4718 ret.append({current, index});
4719 rect |= current;
4720 }
4721 }
4722 QRect clipped = rect & viewportRect;
4723 rect.setLeft(clipped.left());
4724 rect.setRight(clipped.right());
4725 return ret;
4726}
4727
4728QPixmap QAbstractItemViewPrivate::renderToPixmap(const QModelIndexList &indexes, QRect *r) const
4729{
4730 Q_Q(const QAbstractItemView);
4731 Q_ASSERT(r);
4732 const QItemViewPaintPairs paintPairs = draggablePaintPairs(indexes, r);
4733 if (paintPairs.isEmpty())
4734 return QPixmap();
4735
4736 QWindow *window = windowHandle(WindowHandleMode::Closest);
4737 const qreal scale = window ? window->devicePixelRatio() : qreal(1);
4738
4739 QPixmap pixmap(r->size() * scale);
4740 pixmap.setDevicePixelRatio(scale);
4741
4742 pixmap.fill(Qt::transparent);
4743 QPainter painter(&pixmap);
4744 painter.setLayoutDirection(q->layoutDirection());
4745 QStyleOptionViewItem option;
4746 q->initViewItemOption(&option);
4747 option.state |= QStyle::State_Selected;
4748 for (const auto &paintPair : paintPairs) {
4749 option.rect = paintPair.rect.translated(-r->topLeft());
4750 const QModelIndex &current = paintPair.index;
4751 adjustViewOptionsForIndex(&option, current);
4752 q->itemDelegateForIndex(current)->paint(&painter, option, current);
4753 }
4754 return pixmap;
4755}
4756
4757void QAbstractItemViewPrivate::selectAll(QItemSelectionModel::SelectionFlags command)
4758{
4759 if (!selectionModel)
4760 return;
4761 if (!model->hasChildren(root))
4762 return;
4763
4764 QModelIndex tl = model->index(0, 0, root);
4765 QModelIndex br = model->index(model->rowCount(root) - 1,
4766 model->columnCount(root) - 1,
4767 root);
4768 QItemSelection selection({ QItemSelectionRange(tl, br) });
4769 selectionModel->select(selection, command);
4770}
4771
4772#if QT_CONFIG(draganddrop)
4773QModelIndexList QAbstractItemViewPrivate::selectedDraggableIndexes() const
4774{
4775 Q_Q(const QAbstractItemView);
4776 QModelIndexList indexes = q->selectedIndexes();
4777 auto isNotDragEnabled = [this](const QModelIndex &index) {
4778 return !isIndexDragEnabled(index);
4779 };
4780 indexes.removeIf(isNotDragEnabled);
4781 return indexes;
4782}
4783
4784void QAbstractItemViewPrivate::maybeStartDrag(QPoint eventPosition)
4785{
4786 Q_Q(QAbstractItemView);
4787
4788 const QPoint topLeft = pressedPosition - offset();
4789 if ((topLeft - eventPosition).manhattanLength() > QApplication::startDragDistance()) {
4790 pressedIndex = QModelIndex();
4791 q->startDrag(model->supportedDragActions());
4792 q->setState(QAbstractItemView::NoState); // the startDrag will return when the dnd operation
4793 // is done
4794 q->stopAutoScroll();
4795 }
4796}
4797#endif
4798
4799/*!
4800 \reimp
4801*/
4802
4803bool QAbstractItemView::eventFilter(QObject *object, QEvent *event)
4804{
4805 Q_D(QAbstractItemView);
4806 if (object == this || object == viewport() || event->type() != QEvent::FocusIn)
4807 return QAbstractScrollArea::eventFilter(object, event);
4808 QWidget *widget = qobject_cast<QWidget *>(object);
4809 // If it is not a persistent widget then we did not install
4810 // the event filter on it, so assume a base implementation is
4811 // filtering
4812 if (!widget || !d->persistent.contains(widget))
4813 return QAbstractScrollArea::eventFilter(object, event);
4814 setCurrentIndex(d->indexForEditor(widget));
4815 return false;
4816}
4817
4818QT_END_NAMESPACE
4819
4820#include "moc_qabstractitemview.cpp"
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)