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
qrangemodel_impl.h
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#ifndef QRANGEMODEL_IMPL_H
6#define QRANGEMODEL_IMPL_H
7
8#ifndef Q_QDOC
9
10#ifndef QRANGEMODEL_H
11#error Do not include qrangemodel_impl.h directly
12#endif
13
14#if 0
15#pragma qt_sync_skip_header_check
16#pragma qt_sync_stop_processing
17#endif
18
19#include <QtCore/qabstractitemmodel.h>
20#include <QtCore/qcollator.h>
21#include <QtCore/qquasivirtual_impl.h>
22#include <QtCore/qmetaobject.h>
23#include <QtCore/qvariant.h>
24#include <QtCore/qmap.h>
25#include <QtCore/qscopedvaluerollback.h>
26#include <QtCore/qset.h>
27#include <QtCore/qregularexpression.h>
28#include <QtCore/qvarlengtharray.h>
29
30#include <algorithm>
31#include <functional>
32#include <iterator>
33#include <type_traits>
34#include <QtCore/qxptype_traits.h>
35#include <tuple>
36#include <QtCore/q23utility.h>
37
38QT_BEGIN_NAMESPACE
39
40namespace QRangeModelDetails
41{
42 template <typename T, template <typename...> typename... Templates>
44
45 template <template <typename...> typename Template,
46 typename... Params,
47 template <typename...> typename... Templates>
49
50 template <typename T,
51 template <typename...> typename Template,
52 template <typename...> typename... Templates>
54
55 template <typename T, template <typename...> typename... Templates>
57
58 template <typename T, typename = void>
60
61 template <typename T>
62 struct is_validatable<T, std::void_t<decltype(*std::declval<T>())>>
63 : std::is_constructible<bool, T> {};
64
65 template <typename T, typename = void>
67
68 template <typename T>
71 std::is_pointer<decltype(std::declval<T&>().get())>,
72 std::is_same<decltype(*std::declval<T&>().get()), decltype(*std::declval<T&>())>,
74 >>>
75 : std::true_type
76 {};
77
78 // TODO: shouldn't we check is_smart_ptr && !is_copy_constructible && !is_copy_assignable
79 // to support users-specific ptrs?
80 template <typename T>
82#ifndef QT_NO_SCOPED_POINTER
84#endif
86 >;
87
88 template <typename T>
91
92 template <typename T>
94
95 template <typename T>
97
98 template <typename T>
99 static auto pointerTo(T&& t) {
100 using Type = q20::remove_cvref_t<T>;
101 if constexpr (is_any_of<Type, std::optional>())
102 return t ? std::addressof(*std::forward<T>(t)) : nullptr;
103 else if constexpr (std::is_pointer<Type>())
104 return t;
105 else if constexpr (is_smart_ptr<Type>())
106 return t.get();
107 else if constexpr (is_any_of<Type, std::reference_wrapper>())
108 return std::addressof(t.get());
109 else
110 return std::addressof(std::forward<T>(t));
111 }
112
113 template <typename T>
115 {
117 };
118 template <>
119 struct wrapped_helper<void>
120 {
121 using type = void;
122 };
123 template <typename T>
125
126 template <typename T>
129 >>;
130
131 template <typename T, typename = void>
133 template <typename T, std::size_t N>
134 struct tuple_like<std::array<T, N>> : std::false_type {};
135 template <typename T>
138 template <typename T>
139 [[maybe_unused]] static constexpr bool tuple_like_v = tuple_like<T>::value;
140
141 template <typename T, typename = void>
143 template <typename T, std::size_t N>
144 struct array_like<std::array<T, N>> : std::true_type {};
145 template <typename T, std::size_t N>
146 struct array_like<T[N]> : std::true_type {};
147 template <typename T>
148 [[maybe_unused]] static constexpr bool array_like_v = array_like<T>::value;
149
150 template <typename T, typename = void>
152 template <typename T>
155 template <typename T>
156 [[maybe_unused]] static constexpr bool has_metaobject_v = has_metaobject<T>::value;
157
158 template <typename T>
159 static constexpr bool isValid(const T &t) noexcept
160 {
161 if constexpr (std::is_array_v<T>)
162 return true;
163 else if constexpr (is_validatable<T>())
164 return bool(t);
165 else
166 return true;
167 }
168
169 template <typename T>
170 static decltype(auto) refTo(T&& t) {
171 Q_ASSERT(QRangeModelDetails::isValid(t));
172 // it's allowed to move only if the object holds unique ownership of the wrapped data
173 using Type = q20::remove_cvref_t<T>;
174 if constexpr (is_any_of<T, std::optional>())
175 return *std::forward<T>(t); // let std::optional resolve dereferencing
176 if constexpr (!is_wrapped<Type>() || is_any_unique_ptr<Type>())
177 return q23::forward_like<T>(*QRangeModelDetails::pointerTo(t));
178 else
179 return *QRangeModelDetails::pointerTo(t);
180 }
181
182 template <typename It>
183 auto key(It&& it) -> decltype(it.key()) { return std::forward<It>(it).key(); }
184 template <typename It>
185 auto key(It&& it) -> decltype((it->first)) { return std::forward<It>(it)->first; }
186
187 template <typename It>
188 auto value(It&& it) -> decltype(it.value()) { return std::forward<It>(it).value(); }
189 template <typename It>
190 auto value(It&& it) -> decltype((it->second)) { return std::forward<It>(it)->second; }
191
192 // use our own, ADL friendly versions of begin/end so that we can overload
193 // for pointers.
194 using std::begin;
195 using std::end;
196 template <typename C>
197 static auto adl_begin(C &&c) -> decltype(begin(QRangeModelDetails::refTo(std::forward<C>(c))))
198 { return begin(QRangeModelDetails::refTo(std::forward<C>(c))); }
199 template <typename C>
200 static auto adl_end(C &&c) -> decltype(end(QRangeModelDetails::refTo(std::forward<C>(c))))
201 { return end(QRangeModelDetails::refTo(std::forward<C>(c))); }
202 template <typename C>
203 static auto pos(C &&c, int i)
204 { return std::next(QRangeModelDetails::adl_begin(std::forward<C>(c)), i); }
205
206 // Test if a type is a range, and whether we can modify it using the
207 // standard C++ container member functions insert, erase, and resize.
208 // For the sake of QAIM, we cannot modify a range if it holds const data
209 // even if the range itself is not const; we'd need to initialize new rows
210 // and columns, and move old row and column data.
211 template <typename C, typename = void>
213
214 template <typename C>
215 struct test_insert<C, std::void_t<decltype(std::declval<C>().insert(
216 std::declval<typename C::const_iterator>(),
217 std::declval<typename C::size_type>(),
218 std::declval<typename C::value_type>()
219 ))>>
220 : std::true_type
221 {};
222
223 // Can we insert from another (identical) range? Required to support
224 // move-only types
225 template <typename C, typename = void>
227
228 template <typename C>
229 struct test_insert_range<C, std::void_t<decltype(std::declval<C&>().insert(
230 std::declval<typename C::const_iterator&>(),
231 std::declval<std::move_iterator<typename C::iterator>&>(),
232 std::declval<std::move_iterator<typename C::iterator>&>()
233 ))>>
234 : std::true_type
235 {};
236
237 template <typename C, typename = void>
239
240 template <typename C>
241 struct test_erase<C, std::void_t<decltype(std::declval<C>().erase(
242 std::declval<typename C::const_iterator>(),
243 std::declval<typename C::const_iterator>()
244 ))>>
245 : std::true_type
246 {};
247
248 template <typename C, typename = void>
250
251 template <typename C>
252 struct test_resize<C, std::void_t<decltype(std::declval<C>().resize(
253 std::declval<typename C::size_type>(),
254 std::declval<typename C::value_type>()
255 ))>>
256 : std::true_type
257 {};
258
259 // we use std::rotate in moveRows/Columns, which requires the values (which
260 // might be const if we only get a const iterator) to be swappable, and the
261 // iterator type to be at least a forward iterator
262 template <typename It>
263 using test_rotate = std::conjunction<
264 std::is_swappable<decltype(*std::declval<It>())>,
265 std::is_base_of<std::forward_iterator_tag,
266 typename std::iterator_traits<It>::iterator_category>
267 >;
268
269 template <typename C, typename = void>
271
272 template <typename C>
273 struct test_splice<C, std::void_t<decltype(std::declval<C>().splice(
274 std::declval<typename C::const_iterator>(),
275 std::declval<C&>(),
276 std::declval<typename C::const_iterator>(),
277 std::declval<typename C::const_iterator>()
278 ))>>
279 : std::true_type
280 {};
281
282 template <typename C>
283 static void rotate(C& c, int src, int count, int dst) {
284 auto& container = QRangeModelDetails::refTo(c);
285 using Container = std::remove_reference_t<decltype(container)>;
286
287 const auto srcBegin = QRangeModelDetails::pos(container, src);
288 const auto srcEnd = std::next(srcBegin, count);
289 const auto dstBegin = QRangeModelDetails::pos(container, dst);
290
291 if constexpr (test_splice<Container>::value) {
292 if (dst > src && dst < src + count) // dst must be out of the source range
293 container.splice(srcBegin, container, dstBegin, srcEnd);
294 else if (dst != src) // otherwise, std::list gets corrupted
295 container.splice(dstBegin, container, srcBegin, srcEnd);
296 } else {
297 if (src < dst) // moving right
298 std::rotate(srcBegin, srcEnd, dstBegin);
299 else // moving left
300 std::rotate(dstBegin, srcBegin, srcEnd);
301 }
302 }
303
304 // Test if a type is an associative container that we can use for multi-role
305 // data, i.e. has a key_type and a mapped_type typedef, and maps from int,
306 // Qt::ItemDataRole, or QString to QVariant. This excludes std::set (and
307 // unordered_set), which are not useful for us anyway even though they are
308 // considered associative containers.
309 template <typename C, typename = void> struct is_multi_role : std::false_type
310 {
311 static constexpr bool int_key = false;
312 };
313 template <typename C> // Qt::ItemDataRole -> QVariant, or QString -> QVariant, int -> QVariant
314 struct is_multi_role<C, std::void_t<typename C::key_type, typename C::mapped_type>>
315 : std::conjunction<std::disjunction<std::is_same<typename C::key_type, int>,
316 std::is_same<typename C::key_type, Qt::ItemDataRole>,
317 std::is_same<typename C::key_type, QString>>,
318 std::is_same<typename C::mapped_type, QVariant>>
319 {
320 static constexpr bool int_key = !std::is_same_v<typename C::key_type, QString>;
321 };
322 template <typename C>
323 [[maybe_unused]]
324 static constexpr bool is_multi_role_v = is_multi_role<C>::value;
325
326 using std::size;
327 template <typename C, typename = void>
329 template <typename C>
330 struct test_size<C, std::void_t<decltype(size(std::declval<C&>()))>> : std::true_type {};
331
332 template <typename C, typename = void>
334 template <typename C>
335 struct test_cbegin<C, std::void_t<decltype(QRangeModelDetails::adl_begin(std::declval<const C&>()))>>
336 : std::true_type
337 {};
338
339 template <typename C, typename = void>
341 static constexpr bool is_mutable = !std::is_const_v<C>;
342 static constexpr bool has_insert = false;
343 static constexpr bool has_insert_range = false;
344 static constexpr bool has_erase = false;
345 static constexpr bool has_resize = false;
346 static constexpr bool has_rotate = false;
347 static constexpr bool has_splice = false;
348 static constexpr bool has_cbegin = false;
349 };
350 template <typename C>
352 decltype(QRangeModelDetails::adl_end(std::declval<C&>())),
354 >> : std::true_type
355 {
358 static constexpr bool is_mutable = !std::is_const_v<C> && !std::is_const_v<value_type>;
359 static constexpr bool has_insert = test_insert<C>();
360 static constexpr bool has_insert_range = test_insert_range<C>();
361 static constexpr bool has_erase = test_erase<C>();
362 static constexpr bool has_resize = test_resize<C>();
363 static constexpr bool has_rotate = test_rotate<iterator>();
364 static constexpr bool has_splice = test_splice<C>();
365 static constexpr bool has_cbegin = test_cbegin<C>::value;
366 };
367
368 // Specializations for types that look like ranges, but should be
369 // treated as values.
370 enum class Mutable { Yes, No };
371 template <Mutable IsMutable>
373 static constexpr bool is_mutable = IsMutable == Mutable::Yes;
374 static constexpr bool has_insert = false;
375 static constexpr bool has_erase = false;
376 static constexpr bool has_resize = false;
377 static constexpr bool has_rotate = false;
378 static constexpr bool has_splice = false;
379 static constexpr bool has_cbegin = true;
380 };
382 template <> struct range_traits<QString> : iterable_value<Mutable::Yes> {};
383 template <class CharT, class Traits, class Allocator>
386
387 // const T * and views are read-only
388 template <typename T> struct range_traits<const T *> : iterable_value<Mutable::No> {};
390
391 template <typename C>
393 template <typename C>
394 [[maybe_unused]] static constexpr bool is_range_v = is_range<C>();
395
396 // Detect an ItemAccess specialization with static read/writeRole members
397 template <typename T> struct QRangeModelItemAccess;
398
399 template <typename T>
401 {
404
405 template <typename Access, typename Test>
406 using hasReadRole_test = decltype(Access::readRole(std::declval<const Test &>(),
407 Qt::DisplayRole));
408 static constexpr bool hasReadRole = qxp::is_detected_v<hasReadRole_test, ItemAccess, ItemType>;
409
410 template <typename Access, typename Test>
413 static constexpr bool hasWriteRole = qxp::is_detected_v<hasWriteRole_test, ItemAccess, ItemType>;
414
415 template <typename Access, typename Test>
416 using hasFlags_test = decltype(Access::flags(std::declval<const Test&>()));
417
418 static constexpr bool hasFlags = qxp::is_detected_v<hasFlags_test, ItemAccess, ItemType>;
419
420 template <typename Access, typename Test>
421 using hasMimeTypes_test = decltype(Access::mimeTypes());
422 static constexpr bool hasMimeTypes = qxp::is_detected_v<hasMimeTypes_test, ItemAccess, ItemType>;
423
424 template <typename Access, typename Test>
425 using hasMimeData_test = decltype(Access::mimeData(std::declval<QSpan<const Test>>()));
426 static constexpr bool hasMimeData = qxp::is_detected_v<hasMimeData_test, ItemAccess, ItemType>;
427
428 template <typename Access>
430 std::declval<const QMimeData *>()
431 ));
432 static constexpr bool hasCanDropMimeData = qxp::is_detected_v<hasCanDropMimeData_test, ItemAccess>;
433 template <typename Access, typename Test>
435 std::declval<const QMimeData *>(),
437 );
438 static constexpr bool hasDropMimeData = qxp::is_detected_v<hasDropMimeData_test,
439 ItemAccess, ItemType>;
440
441 // full versions with all parameters
442 template <typename Access>
444 std::declval<const QMimeData *>(), Qt::CopyAction, 0, 0, std::declval<const QModelIndex &>()
445 ));
447 ItemAccess>;
448 template <typename Access, typename Test>
450 std::declval<const QMimeData *>(),
451 Qt::CopyAction, 0, 0, std::declval<const QModelIndex &>(),
453 ));
454 static constexpr bool hasDropMimeDataFull = qxp::is_detected_v<hasDropMimeDataFull_test,
455 ItemAccess, ItemType>;
456 };
457
458 // Detect which options are set to override default heuristics. Since
459 // QRangeModel is not yet defined we need to delay the evaluation.
460 template <typename T> struct QRangeModelRowOptions;
461
462 template <typename T, typename = void>
464 {
466 };
467
468 template <typename T>
470 : std::true_type
471 {
473 using RowCategory = decltype(rowCategory);
475 };
476
477 template <typename RowOptions>
479 template <typename row_type>
481
482 template <typename row_type>
483 using hasRowFlags_test = decltype(QRangeModelRowOptions<row_type>::flags(std::declval<const row_type &>()));
484 template <typename row_type>
485 static constexpr bool hasRowFlags = qxp::is_detected_v<hasRowFlags_test, row_type>;
486
487 // drag'n'drop handling
488 template <typename row_type>
489 using hasMimeTypes_test = decltype(QRangeModelRowOptions<row_type>::mimeTypes());
490 template <typename row_type>
491 static constexpr bool hasMimeTypes = qxp::is_detected_v<hasMimeTypes_test, row_type>;
492 template <typename row_type>
494 std::declval<const QModelIndexList &>())
495 );
496 template <typename row_type>
497 static constexpr bool hasMimeDataIndexList = qxp::is_detected_v<hasMimeDataIndexList_test, row_type>;
498 template <typename row_type>
500 // we don't call it with a QSpan, but with a range type. QSpan is a close enough match.
501 std::declval<QSpan<const row_type>>())
502 );
503 template <typename row_type>
504 static constexpr bool hasMimeDataRowSpan = qxp::is_detected_v<hasMimeDataRowSpan_test, row_type>;
505
506 // we allow simplified versions of (can)DropMimeData
507 template <typename row_type>
509 std::declval<const QMimeData *>()
510 ));
511 template <typename row_type>
512 static constexpr bool hasCanDropMimeData = qxp::is_detected_v<hasCanDropMimeData_test, row_type>;
513 template <typename row_type>
515 std::declval<const QMimeData *>(),
517 ));
518 template <typename row_type>
519 static constexpr bool hasDropMimeData = qxp::is_detected_v<hasDropMimeData_test, row_type>;
520
521 // the full versions get all the parameters
522 template <typename row_type>
524 std::declval<const QMimeData *>(), Qt::CopyAction, 0, 0, std::declval<const QModelIndex &>()
525 ));
526 template <typename row_type>
528 row_type>;
529 template <typename row_type>
531 std::declval<const QMimeData *>(),
532 Qt::CopyAction, 0, 0, std::declval<const QModelIndex &>(),
534 ));
535 template <typename row_type>
537 row_type>;
538
539 // Find out how many fixed elements can be retrieved from a row element.
540 // main template for simple values and ranges. Specializing for ranges
541 // is ambiguous with arrays, as they are also ranges
542 template <typename T, typename = void>
543 struct row_traits {
544 static constexpr bool is_range = is_range_v<q20::remove_cvref_t<T>>
546 // A static size of -1 indicates dynamically sized range
547 // A static size of 0 indicates that the specified type doesn't
548 // represent static or dynamic range.
549 static constexpr int static_size = is_range ? -1 : 0;
551 static constexpr int fixed_size() { return 1; }
552 static constexpr bool hasMetaObject = false;
553
555 {
556 return {};
557 }
558
559 template <typename C, typename Fn>
560 static bool for_element_at(C &&container, std::size_t idx, Fn &&fn)
561 {
562 if constexpr (is_range)
563 return std::forward<Fn>(fn)(*QRangeModelDetails::pos(std::forward<C>(container), idx));
564 else
565 return std::forward<Fn>(fn)(std::forward<C>(container));
566 }
567
568 template <typename Fn>
569 static bool for_each_element(const T &row, const QModelIndex &firstIndex, Fn &&fn)
570 {
571 if constexpr (static_size == 0) {
572 return std::forward<Fn>(fn)(firstIndex, QRangeModelDetails::pointerTo(row));
573 } else {
574 int columnIndex = -1;
575 return std::all_of(QRangeModelDetails::adl_begin(row),
576 QRangeModelDetails::adl_end(row), [&](const auto &item) {
577 return std::forward<Fn>(fn)(firstIndex.siblingAtColumn(++columnIndex),
578 QRangeModelDetails::pointerTo(item));
579 });
580 }
581 }
582 };
583
584 // Specialization for tuple-like semantics (prioritized over metaobject)
585 template <typename T>
587 {
588 static constexpr std::size_t size64 = std::tuple_size_v<T>;
589 static_assert(q20::in_range<int>(size64));
590 static constexpr int static_size = int(size64);
591
592 // are the types in a tuple all the same
593 template <std::size_t ...I>
594 static constexpr bool allSameTypes(std::index_sequence<I...>)
595 {
596 return (std::is_same_v<std::tuple_element_t<0, T>,
597 std::tuple_element_t<I, T>> && ...);
598 }
599
601 std::tuple_element_t<0, T>, void>;
602 static constexpr int fixed_size() { return 0; }
603 static constexpr bool hasMetaObject = false;
604
605 template <typename C, typename F>
607 {
609 constexpr size_t size = std::tuple_size_v<type>;
610 Q_ASSERT(idx < size);
611 return QtPrivate::applyIndexSwitch<size>(idx, [&](auto idxConstant) {
613 });
614 }
615
617 {
618 constexpr auto size = std::tuple_size_v<T>;
620
626 >();
627 if (metaType.isValid())
629 });
630 return result;
631 }
632
633 template <typename Fn, std::size_t ...Is>
634 static bool forEachTupleElement(const T &row, Fn &&fn, std::index_sequence<Is...>)
635 {
636 using std::get;
637 return (std::forward<Fn>(fn)(QRangeModelDetails::pointerTo(get<Is>(row))) && ...);
638 }
639
640 template <typename Fn>
641 static bool for_each_element(const T &row, const QModelIndex &firstIndex, Fn &&fn)
642 {
643 int column = -1;
644 return forEachTupleElement(row, [&column, &fn, &firstIndex](const QObject *item){
647 }
648 };
649
650 // Specialization for C arrays and std::array
651 template <typename T, std::size_t N>
652 struct row_traits<std::array<T, N>>
653 {
654 static_assert(q20::in_range<int>(N));
655 static constexpr int static_size = int(N);
656 using item_type = T;
657 static constexpr int fixed_size() { return 0; }
658 static constexpr bool hasMetaObject = false;
659
660 template <typename C, typename F>
666
668 {
669 return section;
670 }
671
672 template <typename Fn>
673 static bool for_each_element(const std::array<T, N> &row, const QModelIndex &firstIndex, Fn &&fn)
674 {
675 int columnIndex = -1;
677 QRangeModelDetails::adl_end(row), [&](const auto &item) {
680 });
681 }
682 };
683
684 template <typename T, std::size_t N>
685 struct row_traits<T[N]> : row_traits<std::array<T, N>> {};
686
687 // prioritize tuple-like over metaobject
688 template <typename T>
690 {
691 static constexpr int static_size = 0;
693 static int fixed_size() {
694 if constexpr (row_category<T>::isMultiRole) {
695 return 1;
696 } else {
697 // Interpret a gadget in a list as a multi-column row item. To make
698 // a list of multi-role items, wrap it into SingleColumn.
699 static const int columnCount = []{
701 return mo.propertyCount() - mo.propertyOffset();
702 }();
703 return columnCount;
704 }
705 }
706
707 static constexpr bool hasMetaObject = true;
708
709 template <typename C, typename F>
711 {
712 return std::forward<F>(function)(std::forward<C>(container));
713 }
714
716 {
718 if (fixed_size() == 1) {
721 } else if (section <= fixed_size()) {
725 }
726 return result;
727 }
728
729 template <typename Fn>
730 static bool for_each_element(const T &row, const QModelIndex &firstIndex, Fn &&fn)
731 {
733 }
734 };
735
736 template <typename T, typename = void>
738 {
739 template <typename That>
740 static QHash<int, QByteArray> roleNames(That *)
741 {
742 return That::roleNamesForSimpleType();
743 }
744 };
745
746 template <>
747 struct item_traits<void>
748 {
749 template <typename That>
751 {
753 }
754 };
755
756 template <typename T>
761
762 template <typename T>
764 {
765 template <typename That>
770 };
771
772 template <typename T>
773 [[maybe_unused]] static constexpr int static_size_v =
775
776 template <typename Range>
778 {
780
781 template <typename R = row_type>
782 auto newRow() -> decltype(R{}) { return R{}; }
783 };
784
785 template <typename Range>
787 {
789
790 template <typename R = row_type,
795 >,
796 bool> = true>
797 auto newRow() -> decltype(R(new QRangeModelDetails::wrapped_t<R>)) {
798 if constexpr (is_any_of<R, std::shared_ptr>())
800 else
801 return R(new QRangeModelDetails::wrapped_t<R>);
802 }
803
804 template <typename R = row_type,
806 auto newRow() -> decltype(R{}) { return R{}; }
807
808 template <typename R = row_type,
810 auto deleteRow(R&& row) -> decltype(delete row) { delete row; }
811 };
812
813 template <typename Range,
817
818 // Default tree traversal protocol implementation for row types that have
819 // the respective member functions. The trailing return type implicitly
820 // removes those functions that are not available.
821 template <typename Range>
823 {
824 template <typename R /*wrapped_row_type*/>
825 auto parentRow(const R& row) const -> decltype(row.parentRow())
826 {
827 return row.parentRow();
828 }
829
830 template <typename R /* = wrapped_row_type*/>
831 auto setParentRow(R &row, R* parent) -> decltype(row.setParentRow(parent))
832 {
833 row.setParentRow(parent);
834 }
835
836 template <typename R /* = wrapped_row_type*/>
837 auto childRows(const R &row) const -> decltype(row.childRows())
838 {
839 return row.childRows();
840 }
841
842 template <typename R /* = wrapped_row_type*/>
843 auto childRows(R &row) -> decltype(row.childRows())
844 {
845 return row.childRows();
846 }
847 };
848
849 template <typename P, typename R>
850 using protocol_parentRow_test = decltype(std::declval<P&>()
852 template <typename P, typename R>
854
855 template <typename P, typename R>
856 using protocol_childRows_test = decltype(std::declval<P&>()
858 template <typename P, typename R>
860
861 template <typename P, typename R>
865 template <typename P, typename R>
867
868 template <typename P, typename R>
871 template <typename P, typename R>
873
874 template <typename P, typename = void>
876 template <typename P>
877 struct protocol_newRow<P, std::void_t<decltype(std::declval<P&>().newRow())>>
878 : std::true_type {};
879
880 template <typename P, typename R, typename = void>
882 template <typename P, typename R>
884 std::void_t<decltype(std::declval<P&>().deleteRow(std::declval<R&&>()))>>
885 : std::true_type {};
886
887 template <typename Range,
888 typename Protocol = DefaultTreeProtocol<Range>,
889 typename R = typename range_traits<Range>::value_type,
890 typename = void>
892
893 template <typename Range, typename Protocol, typename R>
898
899 template <typename Range>
903 >, bool>;
904
905 template <typename Range, typename Protocol = DefaultTreeProtocol<Range>>
910 >, bool>;
911
912 template <typename Range, typename Protocol>
930
931 // Helpers for drag'n'drop:
932 // MimeDataEntry gives customisations access to a pair of either a row or
933 // an item (in form of the underlying type, i.e. unwrapped, as that's what
934 // customizations specialize RowOptions and ItemAccess for), and the
935 // corresponding index, with decomposition support for easy iteration.
936 template <typename Entry>
938 {
940
941 bool isValid() const { return QRangeModelDetails::isValid(m_entry); }
942 const wrapped_entry &entry() const
943 {
944 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<Entry>()) {
945 // While we mark null-items or indexes in null-rows as not draggable,
946 // client code might override that, or explicitly call QRM::mimeData()
947 // with indexes that point at null-rows or -items.
948 if (!QRangeModelDetails::isValid(m_entry)) {
949#ifndef QT_NO_DEBUG
950 qDebug("QRangeModel::mimeData: null-entry, test with isValid before accessing");
951#endif
952 static const wrapped_entry emptyDefault;
953 return QRangeModelDetails::refTo(emptyDefault);
954 }
955 }
956 return std::as_const(QRangeModelDetails::refTo(m_entry));
957 }
958
959 const QModelIndex &index() const { return m_index; }
960
961 template <std::size_t N>
962 friend decltype(auto) get(const MimeDataEntry &entry)
963 {
964 if constexpr (N == 0)
965 return entry.entry();
966 else if constexpr (N == 1)
967 return entry.index();
968 }
969 const Entry &m_entry;
971 };
972} // namespace QRangeModelDetails
973
974QT_END_NAMESPACE
975
976// decomposition protocol
977namespace std {
978template <typename T>
981template <typename T>
984template <typename T>
987} // namespace QRangeModelDetails
988
989QT_BEGIN_NAMESPACE
990
991namespace QRangeModelDetails {
992 // A helper type for drop-support. Client code populates a sequence of
993 // dropped things via an insertion iterator, and those get wrapped in a
994 // DroppedEntry, which allows user code to also specify the position of the
995 // thing in the target model.
996 template <typename Entry>
998 {
999 struct Cell {
1002
1003 // implicit conversion is intentional
1004 Q_IMPLICIT Cell() noexcept : m_row(-1), m_column(-1) {}
1005 Q_IMPLICIT Cell(int row, int column = 0) noexcept : m_row(row), m_column(column) {}
1006
1007 friend bool operator==(const Cell &lhs, const Cell &rhs) noexcept
1008 {
1009 return lhs.m_row == rhs.m_row && lhs.m_column == rhs.m_column;
1010 }
1011 };
1012
1013 // implicit conversion from and to entry is intentional
1020
1021 // we only move the actual data out
1022 operator Entry&&() && { return std::move(m_entry); }
1023
1024 Entry m_entry;
1026 };
1027
1044
1045 template <bool cacheProperties, bool itemsAreQObjects>
1047 static constexpr bool cachesProperties = false;
1048
1050 };
1051
1053 {
1054 static constexpr bool cachesProperties = true;
1056
1058 {
1059 properties.clear();
1060 }
1061 protected:
1062 ~PropertyCache() = default;
1063 };
1064
1065 template <>
1066 struct PropertyData<true, false> : PropertyCache
1067 {};
1068
1070 {
1071 struct Connection {
1073 int role;
1074
1075 friend bool operator==(const Connection &lhs, const Connection &rhs) noexcept
1076 {
1077 return lhs.sender == rhs.sender && lhs.role == rhs.role;
1078 }
1079 friend size_t qHash(const Connection &c, size_t seed) noexcept
1080 {
1081 return qHashMulti(seed, c.sender, c.role);
1082 }
1083 };
1084
1087
1088 protected:
1089 ~ConnectionStorage() = default;
1090 };
1091
1092 template <>
1094 {};
1095
1096 template <>
1097 struct PropertyData<false, true> : PropertyData<false, false>, ConnectionStorage
1098 {
1100 };
1101
1102 // The storage of the model data. We might store it as a pointer, or as a
1103 // (copied- or moved-into) value (or smart pointer). But we always return a
1104 // raw pointer.
1105 template <typename ModelStorage, typename = void>
1113
1114 template <typename ModelStorage>
1123
1124 template <typename ModelStorage, typename PropertyStorage>
1126 PropertyStorage
1127 {
1131
1132 auto model() { return QRangeModelDetails::pointerTo(this->m_model); }
1133 auto model() const { return QRangeModelDetails::pointerTo(this->m_model); }
1134
1135 template <typename Model = ModelStorage>
1136 ModelData(Model &&model)
1138 {}
1139 };
1140} // namespace QRangeModelDetails
1141
1142class QRangeModel;
1143// forward declare so that we can declare friends
1144template <typename, typename, typename> class QRangeModelAdapter;
1145
1147{
1148 using Self = QRangeModelImplBase;
1150
1151public:
1152 // keep in sync with QRangeModel::AutoConnectPolicy
1158
1159 // keep in sync with QRangeModel::DropOperation
1168
1169 // overridable prototypes (quasi-pure-virtual methods)
1171 bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &data, int role);
1172 bool setData(const QModelIndex &index, const QVariant &data, int role);
1173 bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &data);
1174 bool clearItemData(const QModelIndex &index);
1175 bool insertColumns(int column, int count, const QModelIndex &parent);
1176 bool removeColumns(int column, int count, const QModelIndex &parent);
1177 bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destParent, int destColumn);
1178 bool insertRows(int row, int count, const QModelIndex &parent);
1179 bool removeRows(int row, int count, const QModelIndex &parent);
1180 bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destParent, int destRow);
1181
1182 QModelIndex index(int row, int column, const QModelIndex &parent) const;
1183 QModelIndex sibling(int row, int column, const QModelIndex &index) const;
1184 int rowCount(const QModelIndex &parent) const;
1185 int columnCount(const QModelIndex &parent) const;
1186 Qt::ItemFlags flags(const QModelIndex &index) const;
1187 QVariant headerData(int section, Qt::Orientation orientation, int role) const;
1188 QVariant data(const QModelIndex &index, int role) const;
1189 QMap<int, QVariant> itemData(const QModelIndex &index) const;
1190 inline QHash<int, QByteArray> roleNames() const;
1191 QModelIndex parent(const QModelIndex &child) const;
1192
1193 void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const;
1195
1196 void interfaceVersion(int &version) const;
1197 void sort(int column, Qt::SortOrder order);
1198 QModelIndexList match(const QModelIndex &start, int role, const QVariant &value,
1199 int hits, Qt::MatchFlags flags) const;
1200
1201 Qt::DropActions adjustSupportedDragActions(Qt::DropActions dragActions);
1202 Qt::DropActions adjustSupportedDropActions(Qt::DropActions dropActions);
1204 bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column,
1205 const QModelIndex &parent) const;
1206 bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column,
1207 const QModelIndex &parent);
1208 QMimeData *mimeData(const QModelIndexList &indexes) const;
1209
1210 // bindings for overriding
1211
1223
1230 using Data = Method<&Self::data>;
1234
1235 // 6.11
1238
1239 // 6.12
1241 using Sort = Method<&Self::sort>;
1245
1250
1251 template <typename C>
1252 using MethodTemplates = std::tuple<
1253 typename C::Destroy,
1254 typename C::InvalidateCaches,
1255 typename C::SetHeaderData,
1256 typename C::SetData,
1257 typename C::SetItemData,
1258 typename C::ClearItemData,
1259 typename C::InsertColumns,
1260 typename C::RemoveColumns,
1261 typename C::MoveColumns,
1262 typename C::InsertRows,
1263 typename C::RemoveRows,
1264 typename C::MoveRows,
1265 typename C::Index,
1266 typename C::Parent,
1267 typename C::Sibling,
1268 typename C::RowCount,
1269 typename C::ColumnCount,
1270 typename C::Flags,
1271 typename C::HeaderData,
1272 typename C::Data,
1273 typename C::ItemData,
1274 typename C::RoleNames,
1275 typename C::MultiData,
1276 typename C::SetAutoConnectPolicy,
1277 typename C::InterfaceVersion,
1278 typename C::Sort,
1279 typename C::Match,
1280 typename C::AdjustSupportedDragActions,
1281 typename C::AdjustSupportedDropActions,
1282 typename C::MimeTypes,
1283 typename C::CanDropMimeData,
1284 typename C::DropMimeData,
1285 typename C::MimeData
1286 >;
1287
1288 static Q_CORE_EXPORT QRangeModelImplBase *getImplementation(QRangeModel *model);
1289 static Q_CORE_EXPORT const QRangeModelImplBase *getImplementation(const QRangeModel *model);
1290
1291private:
1292 friend class QRangeModelPrivate;
1294
1295 QRangeModel *m_rangeModel;
1296
1297protected:
1298 explicit QRangeModelImplBase(QRangeModel *itemModel)
1299 : m_rangeModel(itemModel)
1300 {}
1301
1302 inline QModelIndex createIndex(int row, int column, const void *ptr = nullptr) const;
1303 inline QModelIndexList persistentIndexList() const;
1304 inline void changePersistentIndex(const QModelIndex &from, const QModelIndex &to);
1305 inline void dataChanged(const QModelIndex &from, const QModelIndex &to,
1306 const QList<int> &roles);
1307 inline void beginResetModel();
1308 inline void endResetModel();
1309 inline void beginInsertColumns(const QModelIndex &parent, int start, int count);
1310 inline void endInsertColumns();
1311 inline void beginRemoveColumns(const QModelIndex &parent, int start, int count);
1312 inline void endRemoveColumns();
1313 inline bool beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast,
1314 const QModelIndex &destParent, int destRow);
1315 inline void endMoveColumns();
1316 inline void beginInsertRows(const QModelIndex &parent, int start, int count);
1317 inline void endInsertRows();
1318 inline void beginRemoveRows(const QModelIndex &parent, int start, int count);
1319 inline void endRemoveRows();
1320 inline bool beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast,
1321 const QModelIndex &destParent, int destRow);
1322 inline void endMoveRows();
1323 inline void beginLayoutChange();
1324 inline void endLayoutChange();
1325 inline AutoConnectPolicy autoConnectPolicy() const;
1326 inline static Qt::partial_ordering compareData(const QVariant &lhs, const QVariant &rhs,
1327 const QCollator *collator);
1328
1329public:
1330 inline QAbstractItemModel &itemModel();
1331 inline const QAbstractItemModel &itemModel() const;
1332
1333 // implemented in qrangemodel.cpp
1335 const QMetaObject &metaObject);
1337
1338protected:
1339 Q_CORE_EXPORT QScopedValueRollback<bool> blockDataChangedDispatch();
1340
1342 const QMetaObject &metaObject);
1344 Q_CORE_EXPORT static bool connectProperty(const QModelIndex &index, const QObject *item,
1345 QRangeModelDetails::AutoConnectContext *context,
1346 int role, const QMetaProperty &property);
1347 Q_CORE_EXPORT static bool connectPropertyConst(const QModelIndex &index, const QObject *item,
1348 QRangeModelDetails::AutoConnectContext *context,
1349 int role, const QMetaProperty &property);
1350 Q_CORE_EXPORT static bool connectProperties(const QModelIndex &index, const QObject *item,
1351 QRangeModelDetails::AutoConnectContext *context,
1352 const QHash<int, QMetaProperty> &properties);
1353 Q_CORE_EXPORT static bool connectPropertiesConst(const QModelIndex &index, const QObject *item,
1354 QRangeModelDetails::AutoConnectContext *context,
1355 const QHash<int, QMetaProperty> &properties);
1356 Q_CORE_EXPORT int sortRole() const;
1357 Q_CORE_EXPORT const QCollator *sortCollator() const;
1358
1359 Q_CORE_EXPORT static QVariant convertMatchValue(const QVariant &value, Qt::MatchFlags flags);
1360 Q_CORE_EXPORT static bool matchValue(const QString &itemData, const QVariant &value,
1361 Qt::MatchFlags flags);
1362 static bool matchValue(const QVariant &itemData, const QVariant &value, Qt::MatchFlags flags)
1363 {
1364 if ((flags & Qt::MatchTypeMask) == Qt::MatchExactly)
1365 return itemData == value;
1366 return matchValue(itemData.toString(), value, flags);
1367 }
1368
1369 Q_CORE_EXPORT bool dropDataOnItem(const QMimeData *data, const QModelIndex &index);
1370};
1371
1372template <typename Structure, typename Range,
1373 typename Protocol = QRangeModelDetails::table_protocol_t<Range>>
1378{
1379public:
1389
1391 typename row_traits::item_type>>;
1393 && row_traits::hasMetaObject; // not treated as tuple
1394
1398 >,
1401 >
1402 >;
1404
1405 using const_row_reference = decltype(*std::declval<typename ModelData::const_iterator&>());
1406
1407 static_assert(!QRangeModelDetails::is_any_of<range_type, std::optional>() &&
1409 "Currently, std::optional is not supported for ranges and rows, as "
1410 "it has range semantics in c++26. Once the required behavior is clarified, "
1411 "std::optional for ranges and rows will be supported.");
1412
1413protected:
1414
1415 using Self = QRangeModelImpl<Structure, Range, Protocol>;
1417
1418 Structure& that() { return static_cast<Structure &>(*this); }
1419 const Structure& that() const { return static_cast<const Structure &>(*this); }
1420
1421 template <typename C>
1422 static constexpr int size(const C &c)
1423 {
1424 if (!QRangeModelDetails::isValid(c))
1425 return 0;
1426
1427 if constexpr (QRangeModelDetails::test_size<C>()) {
1428 using std::size;
1429 return int(size(c));
1430 } else {
1431#if defined(__cpp_lib_ranges)
1432 using std::ranges::distance;
1433#else
1434 using std::distance;
1435#endif
1436 using container_type = std::conditional_t<QRangeModelDetails::range_traits<C>::has_cbegin,
1437 const QRangeModelDetails::wrapped_t<C>,
1438 QRangeModelDetails::wrapped_t<C>>;
1439 container_type& container = const_cast<container_type &>(QRangeModelDetails::refTo(c));
1440 return int(distance(QRangeModelDetails::adl_begin(container),
1441 QRangeModelDetails::adl_end(container)));
1442 }
1443 }
1444
1447 static constexpr bool rows_are_owning_or_raw_pointers =
1450 static constexpr bool one_dimensional_range = static_column_count == 0;
1451
1453 {
1454 if constexpr (itemsAreQObjects || rowsAreQObjects)
1455 return this->blockDataChangedDispatch();
1456 else
1457 return false;
1458 }
1459
1460 // A row might be a value (or range of values), or a pointer.
1461 // row_ptr is always a pointer, and const_row_ptr is a pointer to const.
1464
1465 template <typename T>
1468
1469 // A iterator type to use as the input iterator with the
1470 // range_type::insert(pos, start, end) overload if available (it is in
1471 // std::vector, but not in QList). Generates a prvalue when dereferenced,
1472 // which then gets moved into the newly constructed row, which allows us to
1473 // implement insertRows() for move-only row types.
1475 {
1479 using iterator_category = std::input_iterator_tag;
1480 using difference_type = int;
1481
1482 value_type operator*() { return impl->makeEmptyRow(parentRow); }
1483 EmptyRowGenerator &operator++() { ++n; return *this; }
1484 friend bool operator==(const EmptyRowGenerator &lhs, const EmptyRowGenerator &rhs) noexcept
1485 { return lhs.n == rhs.n; }
1486 friend bool operator!=(const EmptyRowGenerator &lhs, const EmptyRowGenerator &rhs) noexcept
1487 { return !(lhs == rhs); }
1488
1490 Structure *impl = nullptr;
1491 const row_ptr parentRow = nullptr;
1492 };
1493
1494 // If we have a move-only row_type and can add/remove rows, then the range
1495 // must have an insert-from-range overload.
1498 "The range holding a move-only row-type must support insert(pos, start, end)");
1499
1502
1503public:
1504 static constexpr bool isMutable()
1505 {
1506 return range_features::is_mutable && row_features::is_mutable
1507 && std::is_reference_v<row_reference>
1508 && Structure::is_mutable_impl;
1509 }
1510 static constexpr bool dynamicRows() { return isMutable() && static_row_count < 0; }
1511 static constexpr bool dynamicColumns() { return static_column_count < 0; }
1512
1513 explicit QRangeModelImpl(Range &&model, Protocol&& protocol, QRangeModel *itemModel)
1517 {
1518 }
1519
1520
1521 // static interface, called by QRangeModelImplBase
1522
1523 void interfaceVersion(int &versionNumber) const
1524 {
1525 versionNumber = QT_VERSION;
1526 }
1527
1528 void invalidateCaches() { m_data.invalidateCaches(); }
1529
1530 // Not implemented
1531 bool setHeaderData(int , Qt::Orientation , const QVariant &, int ) { return false; }
1532
1533 // actual implementations
1534 QModelIndex index(int row, int column, const QModelIndex &parent) const
1535 {
1536 if (row < 0 || column < 0 || column >= columnCount(parent)
1537 || row >= rowCount(parent)) {
1538 return {};
1539 }
1540
1541 return that().indexImpl(row, column, parent);
1542 }
1543
1544 QModelIndex sibling(int row, int column, const QModelIndex &index) const
1545 {
1546 if (row == index.row() && column == index.column())
1547 return index;
1548
1549 // we use indexes at column -1 in drag'n'drop handling to mark full rows
1550 if (column >= this->columnCount({}))
1551 return {};
1552
1553 if (row == index.row())
1554 return this->createIndex(row, column, index.constInternalPointer());
1555
1556 const_row_ptr parentRow = static_cast<const_row_ptr>(index.constInternalPointer());
1557 const auto siblingCount = size(that().childrenOf(parentRow));
1558 if (row < 0 || row >= int(siblingCount))
1559 return {};
1560 return this->createIndex(row, column, parentRow);
1561 }
1562
1563 Qt::ItemFlags flags(const QModelIndex &index) const
1564 {
1565 if (!index.isValid()) {
1566 if constexpr (isMutable())
1567 return Qt::ItemIsDropEnabled;
1568 else
1569 return Qt::NoItemFlags;
1570 }
1571
1572 // try customization
1573 std::optional<Qt::ItemFlags> customFlags;
1574 if constexpr (QRangeModelDetails::hasRowFlags<wrapped_row_type>) {
1575 const_row_reference row = rowData(index);
1576 if (QRangeModelDetails::isValid(row)) {
1577 customFlags = QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>::flags(
1578 QRangeModelDetails::refTo(row)
1579 );
1580 }
1581 }
1582
1583 readAt(index, [&customFlags](auto &&ref){
1584 Q_UNUSED(ref);
1585 using wrapped_value_type = q20::remove_cvref_t<QRangeModelDetails::wrapped_t<decltype(ref)>>;
1586 if constexpr (QRangeModelDetails::item_access<wrapped_value_type>::hasFlags) {
1587 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<wrapped_value_type>;
1588 if (QRangeModelDetails::isValid(ref)) {
1589 customFlags = ItemAccess::flags(QRangeModelDetails::refTo(ref));
1590 return true;
1591 }
1592 }
1593 return false;
1594 });
1595
1596 Qt::ItemFlags f = customFlags ? *customFlags : Structure::defaultFlags();
1597 // adjust custom flags based on what is not possible
1598 if constexpr (!isMutable())
1599 f &= ~(Qt::ItemIsEditable | Qt::ItemIsDropEnabled);
1600 if (index.column())
1601 f |= Qt::ItemNeverHasChildren;
1602 if (customFlags)
1603 return f;
1604
1605 // compute flags ourselves
1606 if (!this->itemModel().mimeTypes().isEmpty()) {
1607 f |= Qt::ItemIsDragEnabled;
1608 if constexpr (isMutable())
1609 f |= Qt::ItemIsDropEnabled;
1610 }
1611
1612 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<row_type>()) {
1613 // pointer rows might be null
1614 const_row_reference row = rowData(index);
1615 if (!QRangeModelDetails::isValid(row))
1616 f &= ~Qt::ItemIsDragEnabled;
1617 }
1618
1619 if constexpr (isMutable()) {
1620 // Note: Read-only items are still droppable - we can't know here
1621 // whether the model will insert data as new rows or children, or if
1622 // it will overwrite the data of the dropped-on item. So we allow
1623 // dropping on items that are not editable.
1624 if constexpr (row_traits::hasMetaObject) {
1625 if (index.column() < row_traits::fixed_size()) {
1626 const QMetaObject mo = wrapped_row_type::staticMetaObject;
1627 const QMetaProperty prop = mo.property(index.column() + mo.propertyOffset());
1628 if (prop.isWritable())
1629 f |= Qt::ItemIsEditable;
1630 }
1631 } else if constexpr (static_column_count <= 0) {
1632 using item_type = typename row_traits::item_type;
1633 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<item_type>()) {
1634 // pointer items might be null
1635 if (!readAt(index, [](auto &&i){ return QRangeModelDetails::isValid(i); }))
1636 f &= ~Qt::ItemIsDragEnabled;
1637 }
1638 f |= Qt::ItemIsEditable;
1639 } else if constexpr (std::is_reference_v<row_reference> && !std::is_const_v<row_reference>) {
1640 // we want to know if the elements in the tuple are const; they'd always be, if
1641 // we didn't remove the const of the range first.
1642 const_row_reference row = rowData(index);
1643 row_reference mutableRow = const_cast<row_reference>(row);
1644 if (QRangeModelDetails::isValid(mutableRow)) {
1645 row_traits::for_element_at(mutableRow, index.column(), [&f](auto &&ref){
1646 using target_type = decltype(ref);
1647 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<target_type>()) {
1648 // pointer items might be null
1649 if (!QRangeModelDetails::isValid(ref))
1650 f &= ~Qt::ItemIsDragEnabled;
1651 }
1652 if constexpr (std::is_const_v<std::remove_reference_t<target_type>>)
1653 f &= ~Qt::ItemIsEditable;
1654 else if constexpr (std::is_lvalue_reference_v<target_type>)
1655 f |= Qt::ItemIsEditable;
1656 });
1657 } else {
1658 // If there's no usable value stored in the row, then we can't
1659 // do anything with this item, except perhaps drop data into it
1660 f &= ~Qt::ItemIsEditable;
1661 }
1662 }
1663 }
1664 return f;
1665 }
1666
1667 QVariant headerData(int section, Qt::Orientation orientation, int role) const
1668 {
1669 QVariant result;
1670 if constexpr (QRangeModelDetails::hasHeaderData<wrapped_row_type>) {
1671 if (orientation == Qt::Horizontal) {
1672 result = QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>::headerData(
1673 section, role
1674 );
1675 if (result.isValid())
1676 return result;
1677 }
1678 }
1679
1680 if (role != Qt::DisplayRole || orientation != Qt::Horizontal
1681 || section < 0 || section >= columnCount({})) {
1682 return this->itemModel().QAbstractItemModel::headerData(section, orientation, role);
1683 }
1684
1685 result = row_traits::column_name(section);
1686 if (!result.isValid())
1687 result = this->itemModel().QAbstractItemModel::headerData(section, orientation, role);
1688 return result;
1689 }
1690
1691 QVariant data(const QModelIndex &index, int role) const
1692 {
1693 if (!index.isValid())
1694 return {};
1695
1696 QModelRoleData result(role);
1697 multiData(index, result);
1698 return std::move(result.data());
1699 }
1700
1701 static constexpr bool isRangeModelRole(int role)
1702 {
1703 return role == Qt::RangeModelDataRole
1704 || role == Qt::RangeModelAdapterRole;
1705 }
1706
1707 static constexpr bool isPrimaryRole(int role)
1708 {
1709 return role == Qt::DisplayRole || role == Qt::EditRole;
1710 }
1711
1712 QMap<int, QVariant> itemData(const QModelIndex &index) const
1713 {
1714 QMap<int, QVariant> result;
1715
1716 if (index.isValid()) {
1717 // optimisation for items backed by a QMap<int, QVariant> or equivalent
1718 if (!readAt(index, [&result](const auto &value) {
1719 if constexpr (std::is_convertible_v<decltype(value), decltype(result)>) {
1720 result = value;
1721 return true;
1722 }
1723 return false;
1724 })) {
1725 const auto roles = this->itemModel().roleNames().keys();
1726 QVarLengthArray<QModelRoleData, 16> roleDataArray;
1727 roleDataArray.reserve(roles.size());
1728 for (auto role : roles) {
1729 if (isRangeModelRole(role))
1730 continue;
1731 roleDataArray.emplace_back(role);
1732 }
1733 QModelRoleDataSpan roleDataSpan(roleDataArray);
1734 multiData(index, roleDataSpan);
1735
1736 for (QModelRoleData &roleData : roleDataSpan) {
1737 if (roleData.data().isValid())
1738 result[roleData.role()] = std::move(roleData.data());
1739 }
1740 }
1741 }
1742 return result;
1743 }
1744
1746 {
1747 template <typename value_type>
1748 bool operator()(const value_type &value) const
1749 {
1750 using multi_role = QRangeModelDetails::is_multi_role<value_type>;
1751 using wrapped_value_type = QRangeModelDetails::wrapped_t<value_type>;
1752
1753 const auto readModelData = [&value](QModelRoleData &roleData){
1754 if (!QRangeModelDetails::isValid(value)) {
1755 roleData.clearData();
1756 return true;
1757 }
1758
1759 const int role = roleData.role();
1760 if (role == Qt::RangeModelDataRole) {
1761 // Qt QML support: "modelData" role returns the entire multi-role item.
1762 // QML can only use raw pointers to QObject (so we unwrap), and gadgets
1763 // only by value (so we take the reference).
1764 if constexpr (std::is_copy_assignable_v<wrapped_value_type>)
1765 roleData.setData(QVariant::fromValue(QRangeModelDetails::refTo(value)));
1766 else
1767 roleData.setData(QVariant::fromValue(QRangeModelDetails::pointerTo(value)));
1768 } else if (role == Qt::RangeModelAdapterRole) {
1769 // for QRangeModelAdapter however, we want to respect smart pointer wrappers
1770 if constexpr (std::is_copy_assignable_v<value_type>)
1771 roleData.setData(QVariant::fromValue(value));
1772 else
1773 roleData.setData(QVariant::fromValue(QRangeModelDetails::pointerTo(value)));
1774 } else {
1775 return false;
1776 }
1777 return true;
1778 };
1779
1780 if constexpr (QRangeModelDetails::item_access<wrapped_value_type>::hasReadRole) {
1781 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<wrapped_value_type>;
1782 for (auto &roleData : roleDataSpan) {
1783 if (!readModelData(roleData)) {
1784 roleData.setData(ItemAccess::readRole(QRangeModelDetails::refTo(value),
1785 roleData.role()));
1786 }
1787 }
1788 } else if constexpr (multi_role()) {
1789 const auto roleNames = [this]() -> QHash<int, QByteArray> {
1790 Q_UNUSED(this);
1791 if constexpr (!multi_role::int_key)
1792 return that->itemModel().roleNames();
1793 else
1794 return {};
1795 }();
1796 using key_type = typename value_type::key_type;
1797 for (auto &roleData : roleDataSpan) {
1798 const auto &it = [&roleNames, &value, role = roleData.role()]{
1799 Q_UNUSED(roleNames);
1800 if constexpr (multi_role::int_key)
1801 return value.find(key_type(role));
1802 else
1803 return value.find(roleNames.value(role));
1804 }();
1805 if (it != QRangeModelDetails::adl_end(value))
1806 roleData.setData(QRangeModelDetails::value(it));
1807 else
1808 roleData.clearData();
1809 }
1810 } else if constexpr (has_metaobject<value_type>) {
1811 if (row_traits::fixed_size() <= 1) {
1812 for (auto &roleData : roleDataSpan) {
1813 if (!readModelData(roleData)) {
1814 roleData.setData(that->readRole(index, roleData.role(),
1815 QRangeModelDetails::pointerTo(value)));
1816 }
1817 }
1818 } else if (index.column() <= row_traits::fixed_size()) {
1819 for (auto &roleData : roleDataSpan) {
1820 const int role = roleData.role();
1821 if (isPrimaryRole(role)) {
1822 roleData.setData(that->readProperty(index,
1823 QRangeModelDetails::pointerTo(value)));
1824 } else {
1825 roleData.clearData();
1826 }
1827 }
1828 }
1829 } else {
1830 for (auto &roleData : roleDataSpan) {
1831 const int role = roleData.role();
1832 if (isPrimaryRole(role) || isRangeModelRole(role))
1833 roleData.setData(read(value));
1834 else
1835 roleData.clearData();
1836 }
1837 }
1838 return true;
1839 }
1840
1843 const QRangeModelImpl * const that;
1844 };
1845
1846 void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
1847 {
1848 if (!readAt(index, ItemReader{index, roleDataSpan, this})) {
1849 for (auto &roleData : roleDataSpan)
1850 roleData.clearData();
1851 }
1852 }
1853
1854 bool setData(const QModelIndex &index, const QVariant &data, int role)
1855 {
1856 if (!index.isValid())
1857 return false;
1858
1859 if constexpr (isMutable()) {
1860 auto emitDataChanged = qScopeGuard([this, &index, role]{
1861 Q_EMIT this->dataChanged(index, index,
1862 role == Qt::EditRole || role == Qt::RangeModelDataRole
1863 || role == Qt::RangeModelAdapterRole
1864 ? QList<int>{} : QList<int>{role});
1865 });
1866 // we emit dataChanged at the end, block dispatches from auto-connected properties
1867 [[maybe_unused]] auto dataChangedBlocker = maybeBlockDataChangedDispatch();
1868
1869 const auto writeData = [this, column = index.column(), &data, role](auto &&target) -> bool {
1870 using value_type = q20::remove_cvref_t<decltype(target)>;
1871 using wrapped_value_type = QRangeModelDetails::wrapped_t<value_type>;
1872 using multi_role = QRangeModelDetails::is_multi_role<value_type>;
1873
1874 if constexpr (std::conjunction_v<QRangeModelDetails::is_any_owning_ptr<value_type>,
1875 std::is_default_constructible<wrapped_value_type>>) {
1876 if (!QRangeModelDetails::isValid(target))
1877 target.reset(new wrapped_value_type);
1878 }
1879
1880 auto setRangeModelDataRole = [&target, &data]{
1881 constexpr auto targetMetaType = QMetaType::fromType<value_type>();
1882 const auto dataMetaType = data.metaType();
1883 constexpr bool isWrapped = QRangeModelDetails::is_wrapped<value_type>();
1884 if constexpr (!std::is_copy_assignable_v<wrapped_value_type>) {
1885 // we don't support replacing objects that are stored as raw pointers,
1886 // as this makes object ownership very messy. But we can replace objects
1887 // stored in smart pointers, and we can initialize raw nullptr objects.
1888 if constexpr (isWrapped) {
1889 constexpr bool is_raw_pointer = std::is_pointer_v<value_type>;
1890 if constexpr (!is_raw_pointer && std::is_copy_assignable_v<value_type>) {
1891 if (data.canConvert(targetMetaType)) {
1892 target = data.value<value_type>();
1893 return true;
1894 }
1895 } else if constexpr (is_raw_pointer) {
1896 if (!QRangeModelDetails::isValid(target) && data.canConvert(targetMetaType)) {
1897 target = data.value<value_type>();
1898 return true;
1899 }
1900 } else {
1901 Q_UNUSED(target);
1902 }
1903 }
1904 // Otherwise we have a move-only or polymorph type. fall through to
1905 // error handling.
1906 } else if constexpr (isWrapped) {
1907 if (QRangeModelDetails::isValid(target)) {
1908 auto &targetRef = QRangeModelDetails::refTo(target);
1909 // we need to get a wrapped value type out of the QVariant, which
1910 // might carry a pointer. We have to try all alternatives.
1911 if (const auto mt = QMetaType::fromType<wrapped_value_type>();
1912 data.canConvert(mt)) {
1913 targetRef = data.value<wrapped_value_type>();
1914 return true;
1915 } else if (const auto mtp = QMetaType::fromType<wrapped_value_type *>();
1916 data.canConvert(mtp)) {
1917 targetRef = *data.value<wrapped_value_type *>();
1918 return true;
1919 }
1920 }
1921 } else if (targetMetaType == dataMetaType) {
1922 QRangeModelDetails::refTo(target) = data.value<value_type>();
1923 return true;
1924 } else if (dataMetaType.flags() & QMetaType::PointerToGadget) {
1925 QRangeModelDetails::refTo(target) = *data.value<value_type *>();
1926 return true;
1927 }
1928#ifndef QT_NO_DEBUG
1929 qCritical("Not able to assign %s to %s",
1930 qPrintable(QDebug::toString(data)), targetMetaType.name());
1931#endif
1932 return false;
1933 };
1934
1935 if constexpr (QRangeModelDetails::item_access<wrapped_value_type>::hasWriteRole) {
1936 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<wrapped_value_type>;
1937 if (isRangeModelRole(role))
1938 return setRangeModelDataRole();
1939 return ItemAccess::writeRole(QRangeModelDetails::refTo(target), data, role);
1940 } else if constexpr (has_metaobject<value_type>) {
1941 if (row_traits::fixed_size() <= 1) { // multi-role value
1942 if (isRangeModelRole(role))
1943 return setRangeModelDataRole();
1944 return writeRole(role, QRangeModelDetails::pointerTo(target), data);
1945 } else if (column <= row_traits::fixed_size() // multi-column
1946 && (isPrimaryRole(role) || isRangeModelRole(role))) {
1947 return writeProperty(column, QRangeModelDetails::pointerTo(target), data);
1948 }
1949 } else if constexpr (multi_role::value) {
1950 Qt::ItemDataRole roleToSet = Qt::ItemDataRole(role);
1951 // If there is an entry for EditRole, overwrite that; otherwise,
1952 // set the entry for DisplayRole.
1953 const auto roleNames = [this]() -> QHash<int, QByteArray> {
1954 Q_UNUSED(this);
1955 if constexpr (!multi_role::int_key)
1956 return this->itemModel().roleNames();
1957 else
1958 return {};
1959 }();
1960 if (role == Qt::EditRole) {
1961 if constexpr (multi_role::int_key) {
1962 if (target.find(roleToSet) == target.end())
1963 roleToSet = Qt::DisplayRole;
1964 } else {
1965 if (target.find(roleNames.value(roleToSet)) == target.end())
1966 roleToSet = Qt::DisplayRole;
1967 }
1968 }
1969 if constexpr (multi_role::int_key)
1970 return write(target[roleToSet], data);
1971 else
1972 return write(target[roleNames.value(roleToSet)], data);
1973 } else if (isPrimaryRole(role) || isRangeModelRole(role)) {
1974 return write(target, data);
1975 }
1976 return false;
1977 };
1978
1979 if (!writeAt(index, writeData)) {
1980 emitDataChanged.dismiss();
1981 return false;
1982 } else if constexpr (itemsAreQObjects || rowsAreQObjects) {
1983 if (isRangeModelRole(role) && this->autoConnectPolicy() == AutoConnectPolicy::Full) {
1984 if (QObject *item = data.value<QObject *>())
1985 Self::connectProperties(index, item, m_data.context, m_data.properties);
1986 }
1987 }
1988 return true;
1989 }
1990 return false;
1991 }
1992
1993 template <typename LHS, typename RHS>
1994 void updateTarget(LHS &org, RHS &&copy) noexcept
1995 {
1996 if constexpr (std::is_pointer_v<RHS>)
1997 return;
1998 else if constexpr (std::is_assignable_v<LHS, RHS>)
1999 org = std::forward<RHS>(copy);
2000 else
2001 qSwap(org, copy);
2002 }
2003 template <typename LHS, typename RHS>
2004 void updateTarget(LHS *org, RHS &&copy) noexcept
2005 {
2006 updateTarget(*org, std::forward<RHS>(copy));
2007 }
2008
2009 bool setItemData(const QModelIndex &index, const QMap<int, QVariant> &data)
2010 {
2011 if (!index.isValid() || data.isEmpty())
2012 return false;
2013
2014 if constexpr (isMutable()) {
2015 auto emitDataChanged = qScopeGuard([this, &index, &data]{
2016 Q_EMIT this->dataChanged(index, index, data.keys());
2017 });
2018 // we emit dataChanged at the end, block dispatches from auto-connected properties
2019 [[maybe_unused]] auto dataChangedBlocker = maybeBlockDataChangedDispatch();
2020
2021 bool tried = false;
2022 auto writeItemData = [this, &tried, &data](auto &target) -> bool {
2023 Q_UNUSED(this);
2024 using value_type = q20::remove_cvref_t<decltype(target)>;
2025 using multi_role = QRangeModelDetails::is_multi_role<value_type>;
2026 using wrapped_value_type = QRangeModelDetails::wrapped_t<value_type>;
2027
2028 // transactional: if possible, modify a copy and only
2029 // update target if all values from data could be stored.
2030 auto makeCopy = [](const value_type &original){
2031 if constexpr (!std::is_copy_assignable_v<wrapped_value_type>)
2032 return QRangeModelDetails::pointerTo(original); // no transaction support
2033 else if constexpr (std::is_pointer_v<decltype(original)>)
2034 return *original;
2035 else if constexpr (std::is_copy_assignable_v<value_type>)
2036 return original;
2037 else
2038 return QRangeModelDetails::pointerTo(original);
2039 };
2040
2041 const auto roleNames = this->itemModel().roleNames();
2042
2043 if constexpr (QRangeModelDetails::item_access<wrapped_value_type>::hasWriteRole) {
2044 tried = true;
2045 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<wrapped_value_type>;
2046 const auto roles = roleNames.keys();
2047 auto targetCopy = makeCopy(target);
2048 for (int role : roles) {
2049 if (!ItemAccess::writeRole(QRangeModelDetails::refTo(targetCopy),
2050 data.value(role), role)) {
2051 return false;
2052 }
2053 }
2054 updateTarget(target, std::move(targetCopy));
2055 return true;
2056 } else if constexpr (multi_role()) {
2057 using key_type = typename value_type::key_type;
2058 tried = true;
2059 const auto roleName = [&roleNames](int role) {
2060 return roleNames.value(role);
2061 };
2062
2063 // transactional: only update target if all values from data
2064 // can be stored. Storing never fails with int-keys.
2065 if constexpr (!multi_role::int_key)
2066 {
2067 auto invalid = std::find_if(data.keyBegin(), data.keyEnd(),
2068 [&roleName](int role) { return roleName(role).isEmpty(); }
2069 );
2070
2071 if (invalid != data.keyEnd()) {
2072#ifndef QT_NO_DEBUG
2073 qWarning("No role name set for %d", *invalid);
2074#endif
2075 return false;
2076 }
2077 }
2078
2079 for (auto &&[role, value] : data.asKeyValueRange()) {
2080 if constexpr (multi_role::int_key)
2081 target[static_cast<key_type>(role)] = value;
2082 else
2083 target[QString::fromUtf8(roleName(role))] = value;
2084 }
2085 return true;
2086 } else if constexpr (has_metaobject<value_type>) {
2087 if (row_traits::fixed_size() <= 1) {
2088 tried = true;
2089 auto targetCopy = makeCopy(target);
2090 for (auto &&[role, value] : data.asKeyValueRange()) {
2091 if (isRangeModelRole(role))
2092 continue;
2093 if (!writeRole(role, QRangeModelDetails::pointerTo(targetCopy), value)) {
2094 const QByteArray roleName = roleNames.value(role);
2095#ifndef QT_NO_DEBUG
2096 qWarning("Failed to write value '%s' to role '%s'",
2097 qPrintable(QDebug::toString(value)), roleName.data());
2098#endif
2099 return false;
2100 }
2101 }
2102 updateTarget(target, std::move(targetCopy));
2103 return true;
2104 }
2105 }
2106 return false;
2107 };
2108
2109 if (!writeAt(index, writeItemData)) {
2110 emitDataChanged.dismiss();
2111 if (!tried)
2112 return this->itemModel().QAbstractItemModel::setItemData(index, data);
2113 }
2114 return true;
2115 }
2116 return false;
2117 }
2118
2119 bool clearItemData(const QModelIndex &index)
2120 {
2121 if (!index.isValid())
2122 return false;
2123
2124 if constexpr (isMutable()) {
2125 auto emitDataChanged = qScopeGuard([this, &index]{
2126 Q_EMIT this->dataChanged(index, index, {});
2127 });
2128
2129 auto clearData = [column = index.column()](auto &&target) {
2130 if constexpr (row_traits::hasMetaObject) {
2131 if (row_traits::fixed_size() <= 1) {
2132 // multi-role object/gadget: reset all properties
2133 return resetProperty(-1, QRangeModelDetails::pointerTo(target));
2134 } else if (column <= row_traits::fixed_size()) {
2135 return resetProperty(column, QRangeModelDetails::pointerTo(target));
2136 }
2137 } else { // normal structs, values, associative containers
2138 target = {};
2139 return true;
2140 }
2141 return false;
2142 };
2143
2144 if (!writeAt(index, clearData)) {
2145 emitDataChanged.dismiss();
2146 return false;
2147 }
2148 return true;
2149 }
2150 return false;
2151 }
2152
2154 {
2155 // will be 'void' if columns don't all have the same type
2156 using item_type = QRangeModelDetails::wrapped_t<typename row_traits::item_type>;
2157 using item_traits = typename QRangeModelDetails::item_traits<item_type>;
2158 return item_traits::roleNames(this);
2159 }
2160
2161 bool autoConnectPropertiesInRow(const row_type &row, int rowIndex, const QModelIndex &parent) const
2162 {
2163 if (!QRangeModelDetails::isValid(row))
2164 return true; // nothing to do
2165 return row_traits::for_each_element(QRangeModelDetails::refTo(row),
2166 this->itemModel().index(rowIndex, 0, parent),
2167 [this](const QModelIndex &index, const QObject *item) {
2168 if constexpr (isMutable())
2169 return Self::connectProperties(index, item, m_data.context, m_data.properties);
2170 else
2171 return Self::connectPropertiesConst(index, item, m_data.context, m_data.properties);
2172 });
2173 }
2174
2175 void clearConnectionInRow(const row_type &row, int rowIndex, const QModelIndex &parent) const
2176 {
2177 if (!QRangeModelDetails::isValid(row))
2178 return;
2179 row_traits::for_each_element(QRangeModelDetails::refTo(row),
2180 this->itemModel().index(rowIndex, 0, parent),
2181 [this](const QModelIndex &, const QObject *item) {
2182 m_data.connections.removeIf([item](const auto &connection) {
2183 return connection.sender == item;
2184 });
2185 return true;
2186 });
2187 }
2188
2190 {
2191 if constexpr (itemsAreQObjects || rowsAreQObjects) {
2192 using item_type = std::remove_pointer_t<typename row_traits::item_type>;
2193 using Mapping = QRangeModelDetails::AutoConnectContext::AutoConnectMapping;
2194
2195 delete m_data.context;
2196 m_data.connections = {};
2197 switch (this->autoConnectPolicy()) {
2198 case AutoConnectPolicy::None:
2199 m_data.context = nullptr;
2200 break;
2201 case AutoConnectPolicy::Full:
2202 m_data.context = new QRangeModelDetails::AutoConnectContext(&this->itemModel());
2203 if constexpr (itemsAreQObjects) {
2204 m_data.properties = QRangeModelImplBase::roleProperties(this->itemModel(),
2205 item_type::staticMetaObject);
2206 m_data.context->mapping = Mapping::Roles;
2207 } else {
2208 m_data.properties = QRangeModelImplBase::columnProperties(wrapped_row_type::staticMetaObject);
2209 m_data.context->mapping = Mapping::Columns;
2210 }
2211 if (!m_data.properties.isEmpty())
2212 that().autoConnectPropertiesImpl();
2213 break;
2214 case AutoConnectPolicy::OnRead:
2215 m_data.context = new QRangeModelDetails::AutoConnectContext(&this->itemModel());
2216 if constexpr (itemsAreQObjects) {
2217 m_data.context->mapping = Mapping::Roles;
2218 } else {
2219 m_data.properties = QRangeModelImplBase::columnProperties(wrapped_row_type::staticMetaObject);
2220 m_data.context->mapping = Mapping::Columns;
2221 }
2222 break;
2223 }
2224 } else {
2225#ifndef QT_NO_DEBUG
2226 qWarning("All items in the range must be QObject subclasses");
2227#endif
2228 }
2229 }
2230
2231 struct unordered {
2232 friend constexpr bool operator<(unordered, QtPrivate::CompareAgainstLiteralZero) noexcept
2233 { return false; }
2234 friend constexpr bool operator>(unordered, QtPrivate::CompareAgainstLiteralZero) noexcept
2235 { return false; }
2236 };
2237
2238 struct Compare
2239 {
2240 template <typename C, typename LessThan>
2241 using sortMember_test = decltype(std::declval<C&>().sort(std::declval<LessThan &&>()));
2242 static constexpr bool hasSortMember = qxp::is_detected_v<sortMember_test, range_type, Compare>;
2243
2244 template <typename Stringish>
2245 using collatedCompare_test = decltype(
2246 std::declval<const QCollator&>().compare(std::declval<const Stringish&>(),
2247 std::declval<const Stringish&>())
2248 );
2249 template <typename Stringish>
2251 Stringish>;
2252
2253
2254 Compare(const QRangeModelImpl *impl, int column, Qt::SortOrder order)
2255 : that(impl), m_index(impl->createIndex(-1, column, nullptr))
2256 , collator(impl->sortCollator()), m_order(order), m_sortRole(impl->sortRole())
2257 {
2258 }
2259
2260 template <typename Item>
2261 auto operator()(const Item &lhs, const Item &rhs) const
2262 {
2263 auto ordering = compare(lhs, rhs);
2264 return m_order == Qt::AscendingOrder ? ordering < 0 : ordering > 0;
2265 }
2266
2267 template <typename Item>
2268 auto compare(const Item &lhs, const Item &rhs) const
2269 {
2270 using value_type = QRangeModelDetails::wrapped_t<Item>;
2271 using multi_role = QRangeModelDetails::is_multi_role<value_type>;
2272
2273 if constexpr (QRangeModelDetails::item_access<value_type>::hasReadRole
2274 || multi_role() || has_metaobject<value_type>) {
2275 QModelRoleData result(m_sortRole);
2276 // Minor abuse of QModelIndex: the reader needs an index to implement
2277 // lazy auto-connections, but we only have a column. So we construct
2278 // an invalid QModelIndex that carries only that column value. That's
2279 // enough for reading values, and the auto-connection logic skips for
2280 // invalid indexes.
2281 ItemReader reader{m_index, result, that};
2282 Q_ASSERT(!reader.index.isValid());
2283 reader(lhs);
2284 const QVariant lhsVariant = std::move(result.data());
2285 reader(rhs);
2286 const QVariant rhsVariant = std::move(result.data());
2287 return QRangeModelImplBase::compareData(lhsVariant, rhsVariant, collator);
2288 } else if constexpr (std::is_same_v<QVariant, value_type>) {
2289 return QRangeModelImplBase::compareData(lhs, rhs, collator);
2290 } else if constexpr (QtOrderingPrivate::CompareThreeWayTester::hasCompareThreeWay_v
2291 <value_type, value_type>) {
2292 // all types supported by QCollator are also three-way comparable
2293 if constexpr (hasCollatedCompare<value_type>) {
2294 if (collator) {
2295 using ordering = decltype(qCompareThreeWay(lhs, rhs));
2296 int res = collator->compare(lhs, rhs);
2297 if (res < 0)
2298 return ordering::less;
2299 if (res > 0)
2300 return ordering::greater;
2301 return ordering::equal;
2302 }
2303 }
2304 return qCompareThreeWay(lhs, rhs);
2305 } else {
2306 return unordered{};
2307 }
2308 }
2309
2310 bool checkComparable() const
2311 {
2312 return that->readAt(that->index(0, 0, {}), [this](const auto &item){
2313 // before we call std::stable_sort, check that we can compare the
2314 // types we'll ultimately get called with. This doesn't catch cases
2315 // where we end up comparing QVariant, and we cannot make this a
2316 // compile time check as long as readAt etc are not constexpr.
2317 using ordering = decltype(compare(item, item));
2318 if constexpr (std::is_same_v<ordering, unordered>) {
2319#ifndef QT_NO_DEBUG
2320 const QMetaType itemtype = QMetaType::fromType<QRangeModelDetails::wrapped_t<
2321 q20::remove_cvref_t<decltype(item)>>
2322 >();
2323 qCritical("QRangeModel: Cannot compare items of type %s in column %d!",
2324 itemtype.name(), m_index.column());
2325#else
2326 Q_UNUSED(this);
2327#endif
2328 return false;
2329 } else {
2330 return true;
2331 }
2332 });
2333 }
2334
2335 template <typename Item>
2336 static std::optional<bool> compareInvalid(const Item &lhs, const Item &rhs)
2337 {
2338 // invalid data > valid data
2339 if (!QRangeModelDetails::isValid(lhs))
2340 return false;
2341 if (!QRangeModelDetails::isValid(rhs))
2342 return true;
2343 return std::nullopt;
2344 }
2345
2346 const QRangeModelImpl * const that;
2348 const QCollator * const collator;
2350 const int m_sortRole;
2351 };
2352
2353 void sort(int column, Qt::SortOrder order)
2354 {
2355 if constexpr (isMutable() && std::is_swappable_v<row_type>) {
2356 if (rowCount({}) < 2 || column >= columnCount({}))
2357 return;
2358 Compare compare(this, column, order);
2359 if (!compare.checkComparable())
2360 return;
2361
2362 this->beginLayoutChange();
2363 QScopeGuard endLayoutChange([this]{ this->endLayoutChange(); });
2364 that().sortImpl([&compare](const auto &leftRow, const auto &rightRow) {
2365 if (auto anyInvalid = Compare::compareInvalid(leftRow, rightRow))
2366 return *anyInvalid;
2367 return row_traits::for_element_at(leftRow, compare.m_index.column(),
2368 [&rightRow, &compare](const auto &leftItem){
2369 return row_traits::for_element_at(rightRow, compare.m_index.column(),
2370 [&leftItem, &compare](const auto &rightItem){
2371 // Called by std::stable_sort. Since "column" is a runtime value, we
2372 // can't statically assert that lhs and rhs are of the same type.
2373 if constexpr (std::is_same_v<decltype(leftItem), decltype(rightItem)>) {
2374 if (auto anyInvalid = Compare::compareInvalid(leftItem, rightItem))
2375 return *anyInvalid;
2376 return compare(QRangeModelDetails::refTo(leftItem),
2377 QRangeModelDetails::refTo(rightItem));
2378 } else {
2379 Q_UNREACHABLE();
2380 }
2381 return false;
2382 });
2383 });
2384 });
2385 }
2386 }
2387
2388 template <typename LessThan>
2389 void sortSubRange(range_type &range, row_ptr expectedParent, const LessThan &lessThan)
2390 {
2391 auto begin = QRangeModelDetails::adl_begin(range);
2392 auto end = QRangeModelDetails::adl_end(range);
2393 if (begin == end)
2394 return;
2395
2396 QModelIndexList persistentIndexes = this->persistentIndexList();
2397 that().prunePersistentIndexList(persistentIndexes, expectedParent);
2398
2399 if (persistentIndexes.isEmpty()) {
2400 using It = typename range_features::iterator;
2401 constexpr bool is_random_access = std::is_base_of_v<std::random_access_iterator_tag,
2402 typename std::iterator_traits<It>::iterator_category>;
2403 // fast path if we have no persistent indexes: sort the range in place
2404 if constexpr (Compare::hasSortMember) {
2405 range.sort(lessThan);
2406 return;
2407 } else if constexpr (is_random_access) {
2408 std::stable_sort(begin, end, lessThan);
2409 return;
2410 }
2411 }
2412
2413 // slow path: create an indexed version of the range by adding a
2414 // column that records row movements.
2415 struct SortTracker
2416 {
2417 row_type row;
2418 int index;
2419 };
2420
2421 const int rangeSize = size(range);
2422 // Allocate all necessary memory here so that a potential exception
2423 // gets thrown before we have made any modifications.
2424 std::vector<SortTracker> tracked;
2425 tracked.reserve(rangeSize);
2426 std::vector<int> newRows;
2427 newRows.resize(rangeSize);
2428
2429 // move all rows into that index paired with its unsorted position
2430 int row = -1;
2431 for (auto &&it = std::move_iterator(begin); it != std::move_iterator(end); ++it)
2432 tracked.emplace_back(SortTracker{*it, ++row});
2433
2434 // sort the index based on a comparions of the data
2435 std::stable_sort(tracked.begin(), tracked.end(),
2436 [&lessThan](const SortTracker &lhs, const SortTracker &rhs){
2437 return lessThan(lhs.row, rhs.row);
2438 });
2439
2440 // write the values back to the range in (now ordered) sequence,
2441 // and create a mapping from old to new row
2442 auto sorted = std::move_iterator(tracked.begin());
2443 auto write = QRangeModelDetails::adl_begin(range);
2444 qsizetype changedIndexCount = 0;
2445 for (int newIndex = 0; newIndex < rangeSize; ++write, ++sorted, ++newIndex) {
2446 auto &&tracker = *sorted;
2447 changedIndexCount += (tracker.index != newIndex);
2448 *write = std::move(tracker.row);
2449 newRows[tracker.index] = newIndex;
2450 }
2451
2452 // free memory from intermediate vector
2453 tracked.clear();
2454 tracked.shrink_to_fit();
2455
2456 // update relevant persistent model indexes
2457 for (const auto &fromIndex : std::as_const(persistentIndexes)) {
2458 const int newRow = newRows.at(fromIndex.row());
2459 if (fromIndex.row() == newRow)
2460 continue;
2461 const QModelIndex toIndex = that().indexImpl(newRow,
2462 fromIndex.column(),
2463 fromIndex.parent());
2464 this->changePersistentIndex(fromIndex, toIndex);
2465 }
2466 }
2467
2468 QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits,
2469 Qt::MatchFlags flags) const
2470 {
2471 return that().matchImpl(start, role,
2472 QRangeModelImplBase::convertMatchValue(value, flags), hits, flags);
2473 }
2474
2475 bool matchRow(const_row_reference row, const QModelIndex &index, int role, const QVariant &value,
2476 Qt::MatchFlags flags) const
2477 {
2478 const uint matchType = (flags & Qt::MatchTypeMask).toInt();
2479
2480 return row_traits::for_element_at(row, index.column(), [&](const auto &element) {
2481 using value_type = q20::remove_cvref_t<decltype(element)>;
2482 using wrapped_value_type = QRangeModelDetails::wrapped_t<value_type>;
2483 using multi_role = QRangeModelDetails::is_multi_role<value_type>;
2484
2485 if constexpr (QRangeModelDetails::item_access<wrapped_value_type>::hasReadRole
2486 || multi_role() || has_metaobject<value_type>) {
2487 QModelRoleData roleData(role);
2488 ItemReader reader{index, roleData, this};
2489 reader(element);
2490 return QRangeModelImplBase::matchValue(roleData.data(), value, flags);
2491 } else if constexpr (std::is_same_v<wrapped_value_type, QVariant>) {
2492 return QRangeModelImplBase::matchValue(element, value, flags);
2493 } else {
2494 constexpr QMetaType mt = QMetaType::fromType<wrapped_value_type>();
2495 if (mt == value.metaType()) {
2496 if (matchType == Qt::MatchExactly)
2497 return mt.equals(QRangeModelDetails::pointerTo(element), value.constData());
2498 else if constexpr (std::is_same_v<wrapped_value_type, QString>)
2499 return QRangeModelImplBase::matchValue(element, value, flags);
2500 } else {
2501 return QRangeModelImplBase::matchValue(QVariant::fromValue(QRangeModelDetails::refTo(element)),
2502 value, flags);
2503 }
2504 }
2505 return false;
2506 });
2507 }
2508
2509 template <typename InsertFn>
2510 bool doInsertColumns(int column, int count, const QModelIndex &parent, InsertFn insertFn)
2511 {
2512 if (count == 0)
2513 return false;
2514 range_type * const children = childRange(parent);
2515 if (!children)
2516 return false;
2517
2518 this->beginInsertColumns(parent, column, column + count - 1);
2519
2520 for (auto &child : *children) {
2521 auto it = QRangeModelDetails::pos(child, column);
2522 (void)insertFn(QRangeModelDetails::refTo(child), it, count);
2523 }
2524
2525 this->endInsertColumns();
2526
2527 // endInsertColumns emits columnsInserted, at which point clients might
2528 // have populated the new columns with objects (if the columns aren't objects
2529 // themselves).
2530 if constexpr (itemsAreQObjects) {
2531 if (m_data.context && this->autoConnectPolicy() == AutoConnectPolicy::Full) {
2532 for (int r = 0; r < that().rowCount(parent); ++r) {
2533 for (int c = column; c < column + count; ++c) {
2534 const QModelIndex index = that().index(r, c, parent);
2535 writeAt(index, [this, &index](QObject *item){
2536 return Self::connectProperties(index, item,
2537 m_data.context, m_data.properties);
2538 });
2539 }
2540 }
2541 }
2542 }
2543
2544 return true;
2545 }
2546
2547 bool insertColumns(int column, int count, const QModelIndex &parent)
2548 {
2549 if constexpr (dynamicColumns() && isMutable() && row_features::has_insert) {
2550 return doInsertColumns(column, count, parent, [](auto &row, auto it, int n){
2551 row.insert(it, n, {});
2552 return true;
2553 });
2554 } else {
2555 return false;
2556 }
2557 }
2558
2559 bool removeColumns(int column, int count, const QModelIndex &parent)
2560 {
2561 if constexpr (dynamicColumns() && isMutable() && row_features::has_erase) {
2562 if (column < 0 || column + count > columnCount(parent))
2563 return false;
2564
2565 range_type * const children = childRange(parent);
2566 if (!children)
2567 return false;
2568
2569 if constexpr (itemsAreQObjects) {
2570 if (m_data.context && this->autoConnectPolicy() == AutoConnectPolicy::OnRead) {
2571 for (int r = 0; r < that().rowCount(parent); ++r) {
2572 for (int c = column; c < column + count; ++c) {
2573 const QModelIndex index = that().index(r, c, parent);
2574 writeAt(index, [this](QObject *item){
2575 m_data.connections.removeIf([item](const auto &connection) {
2576 return connection.sender == item;
2577 });
2578 return true;
2579 });
2580 }
2581 }
2582 }
2583 }
2584
2585 this->beginRemoveColumns(parent, column, column + count - 1);
2586 for (auto &child : *children) {
2587 const auto start = QRangeModelDetails::pos(child, column);
2588 QRangeModelDetails::refTo(child).erase(start, std::next(start, count));
2589 }
2590 this->endRemoveColumns();
2591 return true;
2592 }
2593 return false;
2594 }
2595
2596 bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count,
2597 const QModelIndex &destParent, int destColumn)
2598 {
2599 // we only support moving columns within the same parent
2600 if (sourceParent != destParent)
2601 return false;
2602 if constexpr (isMutable() && (row_features::has_rotate || row_features::has_splice)) {
2603 if (!Structure::canMoveColumns(sourceParent, destParent))
2604 return false;
2605
2606 if constexpr (dynamicColumns()) {
2607 // we only support ranges as columns, as other types might
2608 // not have the same data type across all columns
2609 range_type * const children = childRange(sourceParent);
2610 if (!children)
2611 return false;
2612
2613 if (!this->beginMoveColumns(sourceParent, sourceColumn, sourceColumn + count - 1,
2614 destParent, destColumn)) {
2615 return false;
2616 }
2617
2618 for (auto &child : *children)
2619 QRangeModelDetails::rotate(child, sourceColumn, count, destColumn);
2620
2621 this->endMoveColumns();
2622 return true;
2623 }
2624 }
2625 return false;
2626 }
2627
2628 template <typename InsertFn>
2629 bool doInsertRows(int row, int count, const QModelIndex &parent, InsertFn &&insertFn)
2630 {
2631 range_type *children = childRange(parent);
2632 if (!children)
2633 return false;
2634
2635 this->beginInsertRows(parent, row, row + count - 1);
2636
2637 row_ptr parentRow = parent.isValid()
2638 ? QRangeModelDetails::pointerTo(this->rowData(parent))
2639 : nullptr;
2640 (void)std::forward<InsertFn>(insertFn)(*children, parentRow, row, count);
2641
2642 // fix the parent in all children of the modified row, as the
2643 // references back to the parent might have become invalid.
2644 that().resetParentInChildren(children);
2645
2646 this->endInsertRows();
2647
2648 // endInsertRows emits rowsInserted, at which point clients might
2649 // have populated the new row with objects (if the rows aren't objects
2650 // themselves).
2651 if constexpr (itemsAreQObjects || rowsAreQObjects) {
2652 if (m_data.context && this->autoConnectPolicy() == AutoConnectPolicy::Full) {
2653 const auto begin = QRangeModelDetails::pos(children, row);
2654 const auto end = std::next(begin, count);
2655 int rowIndex = row;
2656 for (auto it = begin; it != end; ++it, ++rowIndex)
2657 autoConnectPropertiesInRow(*it, rowIndex, parent);
2658 }
2659 }
2660
2661 return true;
2662 }
2663
2664 bool insertRows(int row, int count, const QModelIndex &parent)
2665 {
2666 if constexpr (canInsertRows()) {
2667 return doInsertRows(row, count, parent,
2668 [this](range_type &children, row_ptr parentRow, int r, int n){
2669 EmptyRowGenerator generator{0, &that(), parentRow};
2670
2671 const auto pos = QRangeModelDetails::pos(children, r);
2672 if constexpr (range_features::has_insert_range) {
2673 children.insert(pos, std::move(generator), EmptyRowGenerator{n});
2674 } else if constexpr (rows_are_owning_or_raw_pointers) {
2675 auto start = children.insert(pos, n, nullptr); // MSVC doesn't like row_type{}
2676 std::copy(std::move(generator), EmptyRowGenerator{n}, start);
2677 } else {
2678 children.insert(pos, n, std::move(*generator));
2679 }
2680 return true;
2681 });
2682 } else {
2683 return false;
2684 }
2685 }
2686
2687 bool removeRows(int row, int count, const QModelIndex &parent = {})
2688 {
2689 if constexpr (canRemoveRows()) {
2690 const int prevRowCount = rowCount(parent);
2691 if (row < 0 || row + count > prevRowCount)
2692 return false;
2693
2694 range_type *children = childRange(parent);
2695 if (!children)
2696 return false;
2697
2698 if constexpr (itemsAreQObjects || rowsAreQObjects) {
2699 if (m_data.context && this->autoConnectPolicy() == AutoConnectPolicy::OnRead) {
2700 const auto begin = QRangeModelDetails::pos(children, row);
2701 const auto end = std::next(begin, count);
2702 int rowIndex = row;
2703 for (auto it = begin; it != end; ++it, ++rowIndex)
2704 clearConnectionInRow(*it, rowIndex, parent);
2705 }
2706 }
2707
2708 this->beginRemoveRows(parent, row, row + count - 1);
2709 [[maybe_unused]] bool callEndRemoveColumns = false;
2710 if constexpr (dynamicColumns()) {
2711 // if we remove the last row in a dynamic model, then we no longer
2712 // know how many columns we should have, so they will be reported as 0.
2713 if (prevRowCount == count) {
2714 if (const int columns = columnCount(parent)) {
2715 callEndRemoveColumns = true;
2716 this->beginRemoveColumns(parent, 0, columns - 1);
2717 }
2718 }
2719 }
2720 { // erase invalidates iterators
2721 const auto begin = QRangeModelDetails::pos(children, row);
2722 const auto end = std::next(begin, count);
2723 that().deleteRemovedRows(begin, end);
2724 children->erase(begin, end);
2725 }
2726 // fix the parent in all children of the modified row, as the
2727 // references back to the parent might have become invalid.
2728 that().resetParentInChildren(children);
2729
2730 if constexpr (dynamicColumns()) {
2731 if (callEndRemoveColumns) {
2732 Q_ASSERT(columnCount(parent) == 0);
2733 this->endRemoveColumns();
2734 }
2735 }
2736 this->endRemoveRows();
2737 return true;
2738 } else {
2739 return false;
2740 }
2741 }
2742
2743 bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count,
2744 const QModelIndex &destParent, int destRow)
2745 {
2746 if constexpr (isMutable() && (range_features::has_rotate || range_features::has_splice)) {
2747 if (!Structure::canMoveRows(sourceParent, destParent))
2748 return false;
2749
2750 if (sourceParent != destParent) {
2751 return that().moveRowsAcross(sourceParent, sourceRow, count,
2752 destParent, destRow);
2753 }
2754
2755 if (sourceRow == destRow || sourceRow == destRow - 1 || count <= 0
2756 || sourceRow < 0 || sourceRow + count - 1 >= this->rowCount(sourceParent)
2757 || destRow < 0 || destRow > this->rowCount(destParent)) {
2758 return false;
2759 }
2760
2761 range_type *source = childRange(sourceParent);
2762 // moving within the same range
2763 if (!this->beginMoveRows(sourceParent, sourceRow, sourceRow + count - 1, destParent, destRow))
2764 return false;
2765
2766 QRangeModelDetails::rotate(source, sourceRow, count, destRow);
2767
2768 that().resetParentInChildren(source);
2769
2770 this->endMoveRows();
2771 return true;
2772 } else {
2773 return false;
2774 }
2775 }
2776
2777 const protocol_type& protocol() const { return QRangeModelDetails::refTo(ProtocolStorage::object()); }
2778 protocol_type& protocol() { return QRangeModelDetails::refTo(ProtocolStorage::object()); }
2779
2780 QModelIndex parent(const QModelIndex &child) const { return that().parentImpl(child); }
2781
2782 int rowCount(const QModelIndex &parent) const { return that().rowCountImpl(parent); }
2783
2784 static constexpr int fixedColumnCount()
2785 {
2786 if constexpr (one_dimensional_range)
2787 return row_traits::fixed_size();
2788 else
2789 return static_column_count;
2790 }
2791 int columnCount(const QModelIndex &parent) const { return that().columnCountImpl(parent); }
2792
2793 void destroy() { delete std::addressof(that()); }
2794
2795 Qt::DropActions adjustSupportedDragActions(Qt::DropActions dragActions) {
2796 if constexpr (!isMutable())
2797 dragActions &= ~Qt::MoveAction;
2798 return dragActions;
2799 }
2800 Qt::DropActions adjustSupportedDropActions(Qt::DropActions dropActions)
2801 {
2802 if constexpr (!isMutable())
2803 dropActions = Qt::IgnoreAction;
2804
2805 return dropActions;
2806 }
2807
2809 {
2810 using ItemType = QRangeModelDetails::wrapped_t<typename row_traits::item_type>;
2811 if constexpr (QRangeModelDetails::item_access<ItemType>::hasMimeTypes)
2812 return QRangeModelDetails::QRangeModelItemAccess<ItemType>::mimeTypes();
2813 else if constexpr (QRangeModelDetails::hasMimeTypes<wrapped_row_type>)
2814 return QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>::mimeTypes();
2815 else
2816 return this->itemModel().QAbstractItemModel::mimeTypes();
2817 }
2818
2819 bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column,
2820 const QModelIndex &target) const
2821 {
2822 if constexpr (isMutable()) {
2823 bool canDrop;
2824 using RowOptions = QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>;
2825 using ItemType = QRangeModelDetails::wrapped_t<typename row_traits::item_type>;
2826 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<ItemType>;
2827 if constexpr (QRangeModelDetails::item_access<ItemType>::hasCanDropMimeDataFull) {
2828 canDrop = ItemAccess::canDropMimeData(data, action, row, column, target);
2829 } else if constexpr (QRangeModelDetails::hasCanDropMimeDataFull<wrapped_row_type>) {
2830 canDrop = RowOptions::canDropMimeData(data, action, row, column, target);
2831 } else {
2832 canDrop = this->itemModel().QAbstractItemModel::canDropMimeData(data, action, row,
2833 column, target);
2834 if constexpr (QRangeModelDetails::item_access<ItemType>::hasCanDropMimeData)
2835 canDrop &= ItemAccess::canDropMimeData(data);
2836 else if constexpr (QRangeModelDetails::hasCanDropMimeData<wrapped_row_type>)
2837 canDrop &= RowOptions::canDropMimeData(data);
2838 }
2839 return canDrop;
2840 } else {
2841 return false;
2842 }
2843 }
2844
2845 // orientation == vertical: we drop rows; otherwise we drop individual items
2846 template <Qt::Orientation orient, typename Entry>
2847 bool doDropMimeData(std::vector<QRangeModelDetails::DroppedEntry<Entry>> &droppedEntries,
2848 DropOperation dropOperation, int row, int column, const QModelIndex &target)
2849 {
2850 using DroppedEntry = QRangeModelDetails::DroppedEntry<Entry>;
2851 using Cell = typename DroppedEntry::Cell;
2852 if (dropOperation == DropOperation::DontDrop)
2853 return false;
2854
2855 const bool dropOnTarget = row == -1 && column == -1 && target.isValid();
2856 const QModelIndex parent = dropOperation == DropOperation::InsertAsChildren
2857 ? target.siblingAtColumn(0) : target.parent();
2858
2859 Cell lastCell;
2860 if constexpr (orient == Qt::Horizontal)
2861 lastCell = {0, -1};
2862 else
2863 lastCell = {-1, 0};
2864 int bottomRow = -1;
2865 int rightColumn = -1;
2866 // set the target cell for all dropped entries and find the bottom-right
2867 // cell relative to the drop position
2868 int maxColumn = that().columnCount(parent) - 1;
2869 for (auto &droppedEntry : droppedEntries) {
2870 if (droppedEntry.m_cell == Cell{-1, -1}) {
2871 if constexpr (orient == Qt::Horizontal) {
2872 // auto-inserted items fill all columns before moving to
2873 // the next row
2874 droppedEntry.m_cell = {lastCell.m_row, lastCell.m_column + 1};
2875 if (droppedEntry.m_cell.m_column > maxColumn) {
2876 droppedEntry.m_cell.m_column = 0;
2877 ++droppedEntry.m_cell.m_row;
2878 }
2879 } else {
2880 droppedEntry.m_cell = {lastCell.m_row + 1, lastCell.m_column};
2881 }
2882 }
2883 lastCell = droppedEntry.m_cell;
2884 bottomRow = std::max(lastCell.m_row, bottomRow);
2885 rightColumn = std::max(lastCell.m_column, rightColumn);
2886 }
2887
2888 if (dropOperation == DropOperation::InsertAsChildren) {
2889 row = rowCount(parent);
2890 column = 0;
2891 } else if (dropOnTarget) {
2892 row = target.row();
2893 column = target.column();
2894 } else {
2895 if (row < 0)
2896 row = rowCount(parent);
2897 // dropping into empty space to the right of a table doesn't widen
2898 if (column < 0)
2899 column = 0;
2900 }
2901 const bool overwrite = dropOperation == DropOperation::OverwriteAndIgnore
2902 || dropOperation == DropOperation::OverwriteAndExtend;
2903
2904 // Compute if we need more rows, and try to add them. Abort if that fails.
2905 const int overwriteRows = overwrite
2906 ? std::min(bottomRow + 1, rowCount(parent) - row)
2907 : 0;
2908 const int newRows = dropOperation == DropOperation::OverwriteAndExtend
2909 ? bottomRow - overwriteRows + 1
2910 : (dropOperation == DropOperation::InsertAsChildren
2911 || dropOperation == DropOperation::InsertAsSiblings)
2912 ? bottomRow + 1
2913 : 0;
2914 if (newRows > 0 && !insertRows(row, newRows, parent))
2915 return false;
2916
2917 // Ditto for columns, but InsertAsSiblings/Children only applies to rows
2918 const int overwriteColumns = overwrite
2919 ? std::min(rightColumn + 1, columnCount(parent) - column)
2920 : 0;
2921 const int newColumns = dropOperation == DropOperation::OverwriteAndExtend
2922 ? rightColumn - overwriteColumns + 1 : 0;
2923 if (newColumns > 0 && !insertColumns(column, newColumns, parent))
2924 return false;
2925
2926 // access the target range
2927 range_type *parentRange = that().childRange(parent);
2928 if (!parentRange)
2929 return false;
2930 range_type &targetRange = *parentRange;
2931
2932 int maxRow = that().rowCount(parent) - 1;
2933 maxColumn = that().columnCount(parent) - 1;
2934 auto begin = std::move_iterator(droppedEntries.begin());
2935 auto end = std::move_iterator(droppedEntries.end());
2936 for (; begin != end; ++begin) {
2937 DroppedEntry droppedEntry = *begin;
2938 const Cell cell = {droppedEntry.m_cell.m_row + row, droppedEntry.m_cell.m_column + column};
2939 if (cell.m_row > maxRow || cell.m_column > maxColumn) // Ignore
2940 continue;
2941 auto writeRow = QRangeModelDetails::pos(targetRange, cell.m_row);
2942 if constexpr (orient == Qt::Vertical) { // complete rows
2943 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<row_type>()) {
2944 if (!*writeRow)
2945 *writeRow = this->protocol().newRow();
2946 **writeRow = std::move(droppedEntry);
2947 } else {
2948 *writeRow = std::move(droppedEntry);
2949 }
2950 } else {
2951 row_traits::for_element_at(*writeRow, cell.m_column, [&](auto &item){
2952 using item_type = q20::remove_cvref_t<decltype(item)>;
2953 using wrapped_item_type = QRangeModelDetails::wrapped_t<item_type>;
2954 if constexpr (QRangeModelDetails::is_any_owning_ptr<item_type>()) {
2955 if (!QRangeModelDetails::isValid(item))
2956 item.reset(new wrapped_item_type{std::move(droppedEntry)});
2957 else
2958 *item = std::move(droppedEntry);
2959 } else if (!QRangeModelDetails::isValid(item)) {
2960 return false;
2961 } else {
2962 item = std::move(droppedEntry);
2963 }
2964 return true;
2965 });
2966 }
2967 }
2968
2969 that().resetParentInChildren(&targetRange);
2970
2971 const QModelIndex topLeft = index(row, column, parent);
2972 const QModelIndex bottomRight = orient == Qt::Horizontal
2973 ? sibling(row + bottomRow, column + rightColumn, topLeft)
2974 : sibling(row + bottomRow, maxColumn, topLeft);
2975 this->dataChanged(topLeft, bottomRight, {});
2976
2977 return true;
2978 }
2979
2980 bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column,
2981 const QModelIndex &target)
2982 {
2983 if constexpr (isMutable()) {
2984 if (!canDropMimeData(data, action, row, column, target))
2985 return false;
2986
2987 const bool dropOnTarget = row == -1 && column == -1 && target.isValid();
2988
2989 auto automaticDropOption = [=](auto dropResult){
2990 DropOperation dropOperation;
2991 if constexpr (std::is_same_v<bool, decltype(dropResult)>) {
2992 dropOperation = dropResult ? DropOperation::Automatic
2993 : DropOperation::DontDrop;
2994 } else { // it's a QRangeModel::DropOperation
2995 dropOperation = static_cast<DropOperation>(dropResult);
2996 }
2997
2998 if (dropOperation == DropOperation::Automatic) {
2999 if constexpr (!canInsertRows())
3000 dropOperation = DropOperation::OverwriteAndIgnore;
3001 else if (!dropOnTarget)
3002 dropOperation = DropOperation::InsertAsSiblings;
3003 else if (target.siblingAtColumn(0).flags().testFlag(Qt::ItemNeverHasChildren))
3004 dropOperation = DropOperation::OverwriteAndExtend;
3005 else
3006 dropOperation = DropOperation::InsertAsChildren;
3007 }
3008 return dropOperation;
3009 };
3010
3011 using ItemType = QRangeModelDetails::wrapped_t<typename row_traits::item_type>;
3012 if constexpr (QRangeModelDetails::item_access<ItemType>::hasDropMimeDataFull
3013 || QRangeModelDetails::item_access<ItemType>::hasDropMimeData) {
3014 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<ItemType>;
3015 using DroppedItem = QRangeModelDetails::DroppedEntry<ItemType>;
3016 std::vector<DroppedItem> droppedItems;
3017 DropOperation dropOperation = automaticDropOption([&]{
3018 auto inserter = std::back_inserter(droppedItems);
3019 if constexpr (QRangeModelDetails::item_access<ItemType>::hasDropMimeDataFull)
3020 return ItemAccess::dropMimeData(data, action, row, column, target, inserter);
3021 else
3022 return ItemAccess::dropMimeData(data, inserter);
3023 }());
3024 if (doDropMimeData<Qt::Horizontal>(droppedItems, dropOperation, row, column, target))
3025 return true;
3026 // fall through to try the default mime type
3027 } else if constexpr (QRangeModelDetails::hasDropMimeDataFull<wrapped_row_type>
3028 || QRangeModelDetails::hasDropMimeData<wrapped_row_type>) {
3029 using RowOptions = QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>;
3030 using DroppedRow = QRangeModelDetails::DroppedEntry<wrapped_row_type>;
3031 std::vector<DroppedRow> droppedRows;
3032 DropOperation dropOperation = automaticDropOption([&]{
3033 auto inserter = std::back_inserter(droppedRows);
3034 if constexpr (QRangeModelDetails::hasDropMimeDataFull<wrapped_row_type>)
3035 return RowOptions::dropMimeData(data, action, row, column, target, inserter);
3036 else
3037 return RowOptions::dropMimeData(data, inserter);
3038 }());
3039 if (doDropMimeData<Qt::Vertical>(droppedRows, dropOperation, row, column, target))
3040 return true;
3041 }
3042 // default mime type handling: dropping on item -> try to set the data
3043 if (dropOnTarget && that().dropOnItem(data, target))
3044 return true;
3045 }
3046 return false;
3047 }
3048
3049 // A bidirectional-iterator that, given a list of QModelIndex, dereferences
3050 // to a list of rows or items, plus QModelIndex, without copying any data.
3051 // For segments in indexes covering full rows, we skip over the individual
3052 // indexes and give the dereferenced index a column value of -1.
3054 {
3057 using iterator_category = std::bidirectional_iterator_tag;
3059 using reference [[maybe_unused]] = value_type;
3061 using pointer [[maybe_unused]] = void;
3062
3064 MimeDataRowIterator(base_iterator it, base_iterator begin, base_iterator end,
3065 const QRangeModelImpl *model)
3066 : m_it(it), m_begin(begin), m_end(end), m_model(model)
3067 , m_columnCount(model->columnCount({}))
3068 {
3069 updateCurrentIndexFullRow();
3070 }
3071
3073 {
3074 const QModelIndex &index = *m_it;
3075 return {m_model->rowData(index),
3076 m_currentIndexIsFullRow
3077 ? m_model->createIndex(m_it->row(), -1, m_it->internalPointer()) : index};
3078 }
3079
3081 if (m_currentIndexIsFullRow)
3082 m_it += m_columnCount;
3083 else
3084 ++m_it;
3085 updateCurrentIndexFullRow();
3086 return *this;
3087 }
3088 MimeDataRowIterator operator++(int) { auto tmp = *this; ++(*this); return tmp; }
3089
3091 --m_it;
3092 m_currentIndexIsFullRow = false;
3093 const int lastColumn = m_columnCount - 1;
3094 if (m_it - m_begin >= lastColumn && m_it->column() == lastColumn) {
3095 const QModelIndex &firstInRow = m_it[-lastColumn];
3096 if (m_it->row() == firstInRow.row()
3097 && firstInRow.internalPointer() == m_it->internalPointer()) {
3098 m_currentIndexIsFullRow = true;
3099 m_it -= lastColumn;
3100 }
3101 }
3102 return *this;
3103 }
3104 MimeDataRowIterator operator--(int) { auto tmp = *this; --(*this); return tmp; }
3105
3106 MimeDataRowIterator operator-(difference_type n) const
3107 {
3108 auto tmp = *this; tmp.m_it -= n; return tmp;
3109 }
3110
3111 bool operator==(const MimeDataRowIterator &other) const { return m_it == other.m_it; }
3112 bool operator!=(const MimeDataRowIterator &other) const { return m_it != other.m_it; }
3113
3114 private:
3115 void updateCurrentIndexFullRow()
3116 {
3117 m_currentIndexIsFullRow = false;
3118 if (m_it == m_end || m_it->column() || m_end - m_it < m_columnCount)
3119 return;
3120 const QModelIndex &lastInRow = m_it[m_columnCount - 1];
3121 m_currentIndexIsFullRow = lastInRow.row() == m_it->row()
3122 && lastInRow.internalPointer() == m_it->internalPointer();
3123 }
3124
3125 base_iterator m_it;
3126 base_iterator m_begin;
3127 base_iterator m_end;
3128 const QRangeModelImpl *m_model;
3129 int m_columnCount = 0;
3130 bool m_currentIndexIsFullRow = false;
3131 };
3132
3134 {
3136 // row_traits::item_type is wrapped, and void if not the same for all columns
3138 void *, typename row_traits::item_type>;
3140 using iterator_category = std::bidirectional_iterator_tag;
3142 using reference [[maybe_unused]] = value_type;
3144 using pointer [[maybe_unused]] = void;
3145
3147 {
3148 const QModelIndex &index = *m_it;
3149 // pointer to the item as stored, including wrapping
3150 const item_type *pitem = nullptr;
3151 const auto &row = m_model->rowData(index);
3152 if (QRangeModelDetails::isValid(row)) {
3153 row_traits::for_element_at(QRangeModelDetails::refTo(row), index.column(),
3154 [&pitem](const auto &item){
3155 pitem = &item;
3156 return true;
3157 });
3158 }
3159 if constexpr (QRangeModelDetails::is_owning_or_raw_pointer<item_type>()) {
3160 if (!QRangeModelDetails::isValid(pitem))
3161 return {{}, index};
3162 }
3163 // this will decompose to a [wrapped_item_type, QModelIndex]
3164 return {*pitem, index};
3165 }
3166 MimeDataItemIterator &operator++() { ++m_it; return *this; }
3167 MimeDataItemIterator operator++(int) { auto tmp = *this; ++(*this); return tmp; }
3168
3169 MimeDataItemIterator &operator--() { --m_it; return *this; }
3170 MimeDataItemIterator operator--(int) { auto tmp = *this; --(*this); return tmp; }
3171
3172 MimeDataItemIterator operator-(difference_type n) const
3173 {
3174 auto tmp = *this; tmp.m_it -= n; return tmp;
3175 }
3176
3177 bool operator==(const MimeDataItemIterator &other) const { return m_it == other.m_it; }
3178 bool operator!=(const MimeDataItemIterator &other) const { return m_it != other.m_it; }
3179
3182 };
3183
3184 template <typename Iterator>
3186 Iterator begin() const { return m_begin; }
3187 Iterator end() const { return m_end; }
3188 auto rbegin() const { return std::reverse_iterator(m_end); }
3189 auto rend() const { return std::reverse_iterator(m_begin); }
3190 auto first() const { return *m_begin;}
3191 auto last() const { return *(m_end - 1);}
3192 bool isEmpty() const { return m_begin == m_end; }
3193 bool empty() const { return m_begin == m_end; }
3194 Iterator m_begin;
3195 Iterator m_end;
3196 };
3197
3198 QMimeData *mimeData(const QModelIndexList &indexes) const
3199 {
3200 QMimeData *result = nullptr;
3201 using RowOptions = QRangeModelDetails::QRangeModelRowOptions<wrapped_row_type>;
3202 using ItemType = QRangeModelDetails::wrapped_t<typename row_traits::item_type>;
3203
3204 if constexpr (QRangeModelDetails::item_access<ItemType>::hasMimeData) {
3205 using ItemAccess = QRangeModelDetails::QRangeModelItemAccess<ItemType>;
3206 const auto begin = MimeDataItemIterator{indexes.begin(), this};
3207 const auto end = MimeDataItemIterator{indexes.end(), this};
3208 result = ItemAccess::mimeData(MimeDataRange<MimeDataItemIterator>{begin, end});
3209 } else if constexpr (QRangeModelDetails::hasMimeDataRowSpan<wrapped_row_type>) {
3210 const auto begin = MimeDataRowIterator(indexes.begin(), indexes.begin(), indexes.end(), this);
3211 const auto end = MimeDataRowIterator(indexes.end(), indexes.begin(), indexes.end(), this);
3212 result = RowOptions::mimeData(MimeDataRange<MimeDataRowIterator>{begin, end});
3213 } else if constexpr (QRangeModelDetails::hasMimeDataIndexList<wrapped_row_type>) {
3214 result = RowOptions::mimeData(indexes);
3215 }
3216
3217 return result;
3218 }
3219
3220 template <typename BaseMethod, typename BaseMethod::template Overridden<Self> overridden>
3221 using Override = typename Ancestor::template Override<BaseMethod, overridden>;
3222
3231
3246
3250
3258
3263
3264protected:
3266 {
3268 }
3269
3271 {
3272 // We delete row objects if we are not operating on a reference or pointer
3273 // to a range, as in that case, the owner of the referenced/pointed to
3274 // range also owns the row entries.
3275 // ### Problem: if we get a copy of a range (no matter if shared or not),
3276 // then adding rows will create row objects in the model's copy, and the
3277 // client can never delete those. But copied rows will be the same pointer,
3278 // which we must not delete (as we didn't create them).
3279
3280 static constexpr bool modelCopied = !QRangeModelDetails::is_wrapped<Range>() &&
3281 (std::is_reference_v<Range> || std::is_const_v<std::remove_reference_t<Range>>);
3282
3283 static constexpr bool modelShared = QRangeModelDetails::is_any_shared_ptr<Range>();
3284
3285 static constexpr bool default_row_deleter = protocol_traits::is_default &&
3286 protocol_traits::has_deleteRow;
3287
3288 static constexpr bool ambiguousRowOwnership = (modelCopied || modelShared) &&
3289 rows_are_raw_pointers && default_row_deleter;
3290
3291 static_assert(!ambiguousRowOwnership,
3292 "Using of copied and shared tree and table models with rows as raw pointers, "
3293 "and the default protocol is not allowed due to ambiguity of rows ownership. "
3294 "Move the model in, use another row type, or implement a custom tree protocol.");
3295
3296 if constexpr (protocol_traits::has_deleteRow && !std::is_pointer_v<Range>
3297 && !QRangeModelDetails::is_any_of<Range, std::reference_wrapper>()) {
3298 const auto begin = QRangeModelDetails::adl_begin(*m_data.model());
3299 const auto end = QRangeModelDetails::adl_end(*m_data.model());
3300 that().deleteRemovedRows(begin, end);
3301 }
3302 }
3303
3304 static constexpr bool canInsertRows()
3305 {
3306 if constexpr (dynamicColumns() && !row_features::has_resize) {
3307 // If we operate on dynamic columns and cannot resize a newly
3308 // constructed row, then we cannot insert.
3309 return false;
3310 } else if constexpr (!protocol_traits::has_newRow) {
3311 // We also cannot insert if we cannot create a new row element
3312 return false;
3313 } else if constexpr (!range_features::has_insert_range
3314 && !std::is_copy_constructible_v<row_type>) {
3315 // And if the row is a move-only type, then the range needs to be
3316 // backed by a container that can move-insert default-constructed
3317 // row elements.
3318 return false;
3319 } else {
3320 return Structure::canInsertRowsImpl();
3321 }
3322 }
3323
3324 static constexpr bool canRemoveRows()
3325 {
3326 return Structure::canRemoveRowsImpl();
3327 }
3328
3329 template <typename F>
3330 bool writeAt(const QModelIndex &index, F&& writer)
3331 {
3332 row_reference row = rowData(index);
3333 if (!QRangeModelDetails::isValid(row))
3334 return false;
3335 return row_traits::for_element_at(row, index.column(), [&writer](auto &&target) {
3336 using target_type = decltype(target);
3337 // we can only assign to an lvalue reference
3338 if constexpr (std::is_lvalue_reference_v<target_type>
3339 && !std::is_const_v<std::remove_reference_t<target_type>>) {
3340 return writer(std::forward<target_type>(target));
3341 } else {
3342 return false;
3343 }
3344 });
3345 }
3346
3347 template <typename F>
3348 bool readAt(const QModelIndex &index, F&& reader) const {
3349 const_row_reference row = rowData(index);
3350 if (!QRangeModelDetails::isValid(row))
3351 return false;
3352 return row_traits::for_element_at(row, index.column(), std::forward<F>(reader));
3353 }
3354
3355 template <typename Value>
3356 static QVariant read(const Value &value)
3357 {
3358 if constexpr (std::is_constructible_v<QVariant, Value>)
3359 return QVariant(value);
3360 else
3361 return QVariant::fromValue(value);
3362 }
3363 template <typename Value>
3364 static QVariant read(Value *value)
3365 {
3366 if (value) {
3367 if constexpr (std::is_constructible_v<QVariant, Value *>)
3368 return QVariant(value);
3369 else
3370 return read(*value);
3371 }
3372 return {};
3373 }
3374
3375 template <typename Target>
3376 static bool write(Target &target, const QVariant &value)
3377 {
3378 using Type = std::remove_reference_t<Target>;
3379 if constexpr (std::is_constructible_v<Target, QVariant>) {
3380 target = value;
3381 return true;
3382 } else if (value.canConvert<Type>()) {
3383 target = value.value<Type>();
3384 return true;
3385 }
3386 return false;
3387 }
3388 template <typename Target>
3389 static bool write(Target *target, const QVariant &value)
3390 {
3391 if (target)
3392 return write(*target, value);
3393 return false;
3394 }
3395
3396 template <typename ItemType>
3398 {
3399 struct {
3400 operator QMetaProperty() const {
3401 const QByteArray roleName = that.itemModel().roleNames().value(role);
3402 const QMetaObject &mo = ItemType::staticMetaObject;
3403 if (const int index = mo.indexOfProperty(roleName.data());
3404 index >= 0) {
3405 return mo.property(index);
3406 }
3407 return {};
3408 }
3409 const QRangeModelImpl &that;
3410 const int role;
3411 } findProperty{*this, role};
3412
3413 if constexpr (ModelData::cachesProperties)
3414 return *m_data.properties.tryEmplace(role, findProperty).iterator;
3415 else
3416 return findProperty;
3417 }
3418
3419 void connectPropertyOnRead(const QModelIndex &index, int role,
3420 const QObject *gadget, const QMetaProperty &prop) const
3421 {
3422 if (!index.isValid())
3423 return;
3424 const typename ModelData::Connection connection = {gadget, role};
3425 if (prop.hasNotifySignal() && this->autoConnectPolicy() == AutoConnectPolicy::OnRead
3426 && !m_data.connections.contains(connection)) {
3427 if constexpr (isMutable())
3428 Self::connectProperty(index, gadget, m_data.context, role, prop);
3429 else
3430 Self::connectPropertyConst(index, gadget, m_data.context, role, prop);
3431 m_data.connections.insert(connection);
3432 }
3433 }
3434
3435 template <typename ItemType>
3436 QVariant readRole(const QModelIndex &index, int role, ItemType *gadget) const
3437 {
3438 using item_type = std::remove_pointer_t<ItemType>;
3439 QVariant result;
3440 QMetaProperty prop = roleProperty<item_type>(role);
3441 if (!prop.isValid() && role == Qt::EditRole) {
3442 role = Qt::DisplayRole;
3443 prop = roleProperty<item_type>(Qt::DisplayRole);
3444 }
3445
3446 if (prop.isValid()) {
3447 if constexpr (itemsAreQObjects)
3448 connectPropertyOnRead(index, role, gadget, prop);
3449 result = readProperty(prop, gadget);
3450 }
3451 return result;
3452 }
3453
3454 template <typename ItemType>
3455 QVariant readRole(const QModelIndex &index, int role, const ItemType &gadget) const
3456 {
3457 return readRole(index, role, &gadget);
3458 }
3459
3460 template <typename ItemType>
3461 static QVariant readProperty(const QMetaProperty &prop, ItemType *gadget)
3462 {
3463 if constexpr (std::is_base_of_v<QObject, ItemType>)
3464 return prop.read(gadget);
3465 else
3466 return prop.readOnGadget(gadget);
3467 }
3468
3469 template <typename ItemType>
3470 QVariant readProperty(const QModelIndex &index, ItemType *gadget) const
3471 {
3472 using item_type = std::remove_pointer_t<ItemType>;
3473 const QMetaObject &mo = item_type::staticMetaObject;
3474 const QMetaProperty prop = mo.property(index.column() + mo.propertyOffset());
3475
3476 if constexpr (rowsAreQObjects)
3477 connectPropertyOnRead(index, Qt::DisplayRole, gadget, prop);
3478
3479 return readProperty(prop, gadget);
3480 }
3481
3482 template <typename ItemType>
3483 QVariant readProperty(const QModelIndex &index, const ItemType &gadget) const
3484 {
3485 return readProperty(index, &gadget);
3486 }
3487
3488 template <typename ItemType>
3489 bool writeRole(int role, ItemType *gadget, const QVariant &data)
3490 {
3491 using item_type = std::remove_pointer_t<ItemType>;
3492 auto prop = roleProperty<item_type>(role);
3493 if (!prop.isValid() && role == Qt::EditRole)
3494 prop = roleProperty<item_type>(Qt::DisplayRole);
3495
3496 return prop.isValid() ? writeProperty(prop, gadget, data) : false;
3497 }
3498
3499 template <typename ItemType>
3500 bool writeRole(int role, ItemType &&gadget, const QVariant &data)
3501 {
3502 return writeRole(role, &gadget, data);
3503 }
3504
3505 template <typename ItemType>
3506 static bool writeProperty(const QMetaProperty &prop, ItemType *gadget, const QVariant &data)
3507 {
3508 if constexpr (std::is_base_of_v<QObject, ItemType>)
3509 return prop.write(gadget, data);
3510 else
3511 return prop.writeOnGadget(gadget, data);
3512 }
3513 template <typename ItemType>
3514 static bool writeProperty(int property, ItemType *gadget, const QVariant &data)
3515 {
3516 using item_type = std::remove_pointer_t<ItemType>;
3517 const QMetaObject &mo = item_type::staticMetaObject;
3518 return writeProperty(mo.property(property + mo.propertyOffset()), gadget, data);
3519 }
3520
3521 template <typename ItemType>
3522 static bool writeProperty(int property, ItemType &&gadget, const QVariant &data)
3523 {
3524 return writeProperty(property, &gadget, data);
3525 }
3526
3527 template <typename ItemType>
3528 static bool resetProperty(int property, ItemType *object)
3529 {
3530 using item_type = std::remove_pointer_t<ItemType>;
3531 const QMetaObject &mo = item_type::staticMetaObject;
3532 bool success = true;
3533 if (property == -1) {
3534 // reset all properties
3535 if constexpr (std::is_base_of_v<QObject, item_type>) {
3536 for (int p = mo.propertyOffset(); p < mo.propertyCount(); ++p)
3537 success = writeProperty(mo.property(p), object, {}) && success;
3538 } else { // reset a gadget by assigning a default-constructed
3539 *object = {};
3540 }
3541 } else {
3542 success = writeProperty(mo.property(property + mo.propertyOffset()), object, {});
3543 }
3544 return success;
3545 }
3546
3547 template <typename ItemType>
3548 static bool resetProperty(int property, ItemType &&object)
3549 {
3550 return resetProperty(property, &object);
3551 }
3552
3553 // helpers
3554 const_row_reference rowData(const QModelIndex &index) const
3555 {
3556 Q_ASSERT(index.isValid());
3557 return that().rowDataImpl(index);
3558 }
3559
3560 row_reference rowData(const QModelIndex &index)
3561 {
3562 Q_ASSERT(index.isValid());
3563 return that().rowDataImpl(index);
3564 }
3565
3566 const range_type *childRange(const QModelIndex &index) const
3567 {
3568 if (!index.isValid())
3569 return m_data.model();
3570 if (index.column()) // only items at column 0 can have children
3571 return nullptr;
3572 return that().childRangeImpl(index);
3573 }
3574
3575 range_type *childRange(const QModelIndex &index)
3576 {
3577 if (!index.isValid())
3578 return m_data.model();
3579 if (index.column()) // only items at column 0 can have children
3580 return nullptr;
3581 return that().childRangeImpl(index);
3582 }
3583
3584 template <typename, typename, typename> friend class QRangeModelAdapter;
3585
3587};
3588
3589// Implementations that depends on the model structure (flat vs tree) that will
3590// be specialized based on a protocol type. The main template implements tree
3591// support through a protocol type.
3592template <typename Range, typename Protocol>
3594 : public QRangeModelImpl<QGenericTreeItemModelImpl<Range, Protocol>, Range, Protocol>
3595{
3596 using Base = QRangeModelImpl<QGenericTreeItemModelImpl<Range, Protocol>, Range, Protocol>;
3597 friend class QRangeModelImpl<QGenericTreeItemModelImpl<Range, Protocol>, Range, Protocol>;
3598
3599 using range_type = typename Base::range_type;
3600 using range_features = typename Base::range_features;
3601 using row_type = typename Base::row_type;
3602 using row_ptr = typename Base::row_ptr;
3603 using const_row_ptr = typename Base::const_row_ptr;
3604
3605 using tree_traits = typename Base::protocol_traits;
3606 static constexpr bool is_mutable_impl = tree_traits::has_mutable_childRows;
3607
3608 static constexpr bool rows_are_any_refs_or_pointers = Base::rows_are_raw_pointers ||
3609 QRangeModelDetails::is_smart_ptr<row_type>() ||
3610 QRangeModelDetails::is_any_of<row_type, std::reference_wrapper>();
3611 static_assert(!Base::dynamicColumns(), "A tree must have a static number of columns!");
3612
3613public:
3614 QGenericTreeItemModelImpl(Range &&model, Protocol &&p, QRangeModel *itemModel)
3615 : Base(std::forward<Range>(model), std::forward<Protocol>(p), itemModel)
3616 {};
3617
3618 void setParentRow(range_type &children, row_ptr parent)
3619 {
3620 for (auto &&child : children)
3621 this->protocol().setParentRow(QRangeModelDetails::refTo(child), parent);
3622 resetParentInChildren(&children);
3623 }
3624
3625 void deleteRemovedRows(range_type &range)
3626 {
3627 deleteRemovedRows(QRangeModelDetails::adl_begin(range), QRangeModelDetails::adl_end(range));
3628 }
3629
3630 bool autoConnectProperties(const QModelIndex &parent) const
3631 {
3632 auto *children = this->childRange(parent);
3633 if (!children)
3634 return true;
3635 return autoConnectPropertiesRange(QRangeModelDetails::refTo(children), parent);
3636 }
3637
3638protected:
3639 QModelIndex indexImpl(int row, int column, const QModelIndex &parent) const
3640 {
3641 if (!parent.isValid())
3642 return this->createIndex(row, column);
3643 // only items at column 0 can have children
3644 if (parent.column())
3645 return QModelIndex();
3646
3647 const_row_ptr grandParent = static_cast<const_row_ptr>(parent.constInternalPointer());
3648 const auto &parentSiblings = childrenOf(grandParent);
3649 const auto it = QRangeModelDetails::pos(parentSiblings, parent.row());
3650 return this->createIndex(row, column, QRangeModelDetails::pointerTo(*it));
3651 }
3652
3653 QModelIndex parentImpl(const QModelIndex &child) const
3654 {
3655 if (!child.isValid())
3656 return {};
3657
3658 // no pointer to parent row - no parent
3659 const_row_ptr parentRow = static_cast<const_row_ptr>(child.constInternalPointer());
3660 if (!parentRow)
3661 return {};
3662
3663 // get the siblings of the parent via the grand parent
3664 auto &&grandParent = this->protocol().parentRow(QRangeModelDetails::refTo(parentRow));
3665 const range_type &parentSiblings = childrenOf(QRangeModelDetails::pointerTo(grandParent));
3666 // find the index of parentRow
3667 const auto begin = QRangeModelDetails::adl_begin(parentSiblings);
3668 const auto end = QRangeModelDetails::adl_end(parentSiblings);
3669 const auto it = std::find_if(begin, end, [parentRow](auto &&s){
3670 return QRangeModelDetails::pointerTo(std::forward<decltype(s)>(s)) == parentRow;
3671 });
3672 if (it != end)
3673 return this->createIndex(std::distance(begin, it), 0,
3674 QRangeModelDetails::pointerTo(grandParent));
3675 return {};
3676 }
3677
3678 int rowCountImpl(const QModelIndex &parent) const
3679 {
3680 return Base::size(this->childRange(parent));
3681 }
3682
3683 int columnCountImpl(const QModelIndex &) const
3684 {
3685 // All levels of a tree have to have the same, fixed, column count.
3686 // If static_column_count is -1 for a tree, static assert fires
3687 return Base::fixedColumnCount();
3688 }
3689
3690 static constexpr Qt::ItemFlags defaultFlags()
3691 {
3692 return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
3693 }
3694
3695 static constexpr bool canInsertRowsImpl()
3696 {
3697 // We must not insert rows if we cannot adjust the parents of the
3698 // children of the following rows. We don't have to do that if the
3699 // range operates on pointers.
3700 return (rows_are_any_refs_or_pointers || tree_traits::has_setParentRow)
3701 && Base::dynamicRows() && range_features::has_insert;
3702 }
3703
3704 static constexpr bool canRemoveRowsImpl()
3705 {
3706 // We must not remove rows if we cannot adjust the parents of the
3707 // children of the following rows. We don't have to do that if the
3708 // range operates on pointers.
3709 return (rows_are_any_refs_or_pointers || tree_traits::has_setParentRow)
3710 && Base::dynamicRows() && range_features::has_erase;
3711 }
3712
3713 static constexpr bool canMoveColumns(const QModelIndex &, const QModelIndex &)
3714 {
3715 return true;
3716 }
3717
3718 static constexpr bool canMoveRows(const QModelIndex &, const QModelIndex &)
3719 {
3720 return true;
3721 }
3722
3723 bool moveRowsAcross(const QModelIndex &sourceParent, int sourceRow, int count,
3724 const QModelIndex &destParent, int destRow)
3725 {
3726 // If rows are pointers, then reference to the parent row don't
3727 // change, so we can move them around freely. Otherwise we need to
3728 // be able to explicitly update the parent pointer.
3729 if constexpr (!rows_are_any_refs_or_pointers && !tree_traits::has_setParentRow) {
3730 return false;
3731 } else if constexpr (!(range_features::has_insert && range_features::has_erase)) {
3732 return false;
3733 } else if (!this->beginMoveRows(sourceParent, sourceRow, sourceRow + count - 1,
3734 destParent, destRow)) {
3735 return false;
3736 }
3737
3738 range_type *source = this->childRange(sourceParent);
3739 range_type *destination = this->childRange(destParent);
3740
3741 // If we can insert data from another range into, then
3742 // use that to move the old data over.
3743 const auto destStart = QRangeModelDetails::pos(destination, destRow);
3744 if constexpr (range_features::has_insert_range) {
3745 const auto sourceStart = QRangeModelDetails::pos(*source, sourceRow);
3746 const auto sourceEnd = std::next(sourceStart, count);
3747
3748 destination->insert(destStart, std::move_iterator(sourceStart),
3749 std::move_iterator(sourceEnd));
3750 } else if constexpr (std::is_copy_constructible_v<row_type>) {
3751 // otherwise we have to make space first, and copy later.
3752 destination->insert(destStart, count, row_type{});
3753 }
3754
3755 row_ptr parentRow = destParent.isValid()
3756 ? QRangeModelDetails::pointerTo(this->rowData(destParent))
3757 : nullptr;
3758
3759 // if the source's parent was already inside the new parent row,
3760 // then the source row might have become invalid, so reset it.
3761 if (parentRow == static_cast<row_ptr>(sourceParent.internalPointer())) {
3762 if (sourceParent.row() < destRow) {
3763 source = this->childRange(sourceParent);
3764 } else {
3765 // the source parent moved down within destination
3766 source = this->childRange(this->createIndex(sourceParent.row() + count, 0,
3767 sourceParent.internalPointer()));
3768 }
3769 }
3770
3771 // move the data over and update the parent pointer
3772 {
3773 const auto writeStart = QRangeModelDetails::pos(destination, destRow);
3774 const auto writeEnd = std::next(writeStart, count);
3775 const auto sourceStart = QRangeModelDetails::pos(source, sourceRow);
3776 const auto sourceEnd = std::next(sourceStart, count);
3777
3778 for (auto write = writeStart, read = sourceStart; write != writeEnd; ++write, ++read) {
3779 // move data over if not already done, otherwise
3780 // only fix the parent pointer
3781 if constexpr (!range_features::has_insert_range)
3782 *write = std::move(*read);
3783 this->protocol().setParentRow(QRangeModelDetails::refTo(*write), parentRow);
3784 }
3785 // remove the old rows from the source parent
3786 source->erase(sourceStart, sourceEnd);
3787 }
3788
3789 // Fix the parent pointers in children of both source and destination
3790 // ranges, as the references to the entries might have become invalid.
3791 // We don't have to do that if the rows are pointers, as in that case
3792 // the references to the entries are stable.
3793 resetParentInChildren(destination);
3795
3796 this->endMoveRows();
3797 return true;
3798 }
3799
3800 auto makeEmptyRow(row_ptr parentRow)
3801 {
3802 // tree traversal protocol: if we are here, then it must be possible
3803 // to change the parent of a row.
3804 static_assert(tree_traits::has_setParentRow);
3805 row_type empty_row = this->protocol().newRow();
3806 if (QRangeModelDetails::isValid(empty_row) && parentRow)
3807 this->protocol().setParentRow(QRangeModelDetails::refTo(empty_row), parentRow);
3808 return empty_row;
3809 }
3810
3811 template <typename It, typename Sentinel>
3812 void deleteRemovedRows(It &&begin, Sentinel &&end)
3813 {
3814 if constexpr (tree_traits::has_deleteRow) {
3815 for (auto it = begin; it != end; ++it) {
3816 if constexpr (Base::isMutable()) {
3817 decltype(auto) children = this->protocol().childRows(QRangeModelDetails::refTo(*it));
3818 if (QRangeModelDetails::isValid(children)) {
3819 deleteRemovedRows(QRangeModelDetails::adl_begin(children),
3820 QRangeModelDetails::adl_end(children));
3821 QRangeModelDetails::refTo(children) = range_type{ };
3822 }
3823 }
3824
3825 this->protocol().deleteRow(std::move(*it));
3826 }
3827 }
3828 }
3829
3830 void resetParentInChildren(range_type *children)
3831 {
3832 const auto persistentIndexList = this->persistentIndexList();
3833 const auto [firstColumn, lastColumn] = [&persistentIndexList]{
3834 int first = std::numeric_limits<int>::max();
3835 int last = -1;
3836 for (const auto &pmi : persistentIndexList) {
3837 first = (std::min)(pmi.column(), first);
3838 last = (std::max)(pmi.column(), last);
3839 }
3840 return std::pair(first, last);
3841 }();
3842
3843 resetParentInChildrenRecursive(children, firstColumn, lastColumn);
3844 }
3845
3846 void resetParentInChildrenRecursive(range_type *children, int pmiFromColumn, int pmiToColumn)
3847 {
3848 if constexpr (tree_traits::has_setParentRow && !rows_are_any_refs_or_pointers) {
3849 const bool changePersistentIndexes = pmiToColumn >= pmiFromColumn;
3850 const auto begin = QRangeModelDetails::adl_begin(*children);
3851 const auto end = QRangeModelDetails::adl_end(*children);
3852 for (auto it = begin; it != end; ++it) {
3853 decltype(auto) maybeChildren = this->protocol().childRows(*it);
3854 if (QRangeModelDetails::isValid(maybeChildren)) {
3855 auto &childrenRef = QRangeModelDetails::refTo(maybeChildren);
3856 auto *parentRow = QRangeModelDetails::pointerTo(*it);
3857
3858 int row = 0;
3859 for (auto &child : childrenRef) {
3860 const_row_ptr oldParent = this->protocol().parentRow(child);
3861 if (oldParent != parentRow) {
3862 if (changePersistentIndexes) {
3863 for (int column = pmiFromColumn; column <= pmiToColumn; ++column) {
3864 this->changePersistentIndex(this->createIndex(row, column, oldParent),
3865 this->createIndex(row, column, parentRow));
3866 }
3867 }
3868 this->protocol().setParentRow(child, parentRow);
3869 }
3870 ++row;
3871 }
3872 resetParentInChildrenRecursive(&childrenRef, pmiFromColumn, pmiToColumn);
3873 }
3874 }
3875 }
3876 }
3877
3878 bool autoConnectPropertiesRange(const range_type &range, const QModelIndex &parent) const
3879 {
3880 int rowIndex = 0;
3881 for (const auto &row : range) {
3882 if (!this->autoConnectPropertiesInRow(row, rowIndex, parent))
3883 return false;
3884 Q_ASSERT(QRangeModelDetails::isValid(row));
3885 const auto &children = this->protocol().childRows(QRangeModelDetails::refTo(row));
3886 if (QRangeModelDetails::isValid(children)) {
3887 if (!autoConnectPropertiesRange(QRangeModelDetails::refTo(children),
3888 this->itemModel().index(rowIndex, 0, parent))) {
3889 return false;
3890 }
3891 }
3892 ++rowIndex;
3893 }
3894 return true;
3895 }
3896
3898 {
3899 return autoConnectPropertiesRange(*this->m_data.model(), {});
3900 }
3901
3902 decltype(auto) rowDataImpl(const QModelIndex &index) const
3903 {
3904 const_row_ptr parentRow = static_cast<const_row_ptr>(index.constInternalPointer());
3905 const range_type &siblings = childrenOf(parentRow);
3906 Q_ASSERT(index.row() < int(Base::size(siblings)));
3907 return *QRangeModelDetails::pos(siblings, index.row());
3908 }
3909
3910 decltype(auto) rowDataImpl(const QModelIndex &index)
3911 {
3912 row_ptr parentRow = static_cast<row_ptr>(index.internalPointer());
3913 range_type &siblings = childrenOf(parentRow);
3914 Q_ASSERT(index.row() < int(Base::size(siblings)));
3915 return *QRangeModelDetails::pos(siblings, index.row());
3916 }
3917
3918 const range_type *childRangeImpl(const QModelIndex &index) const
3919 {
3920 const auto &row = this->rowData(index);
3921 if (!QRangeModelDetails::isValid(row))
3922 return static_cast<const range_type *>(nullptr);
3923
3924 decltype(auto) children = this->protocol().childRows(QRangeModelDetails::refTo(row));
3925 return QRangeModelDetails::pointerTo(std::forward<decltype(children)>(children));
3926 }
3927
3928 range_type *childRangeImpl(const QModelIndex &index)
3929 {
3930 auto &row = this->rowData(index);
3931 if (!QRangeModelDetails::isValid(row))
3932 return static_cast<range_type *>(nullptr);
3933
3934 decltype(auto) children = this->protocol().childRows(QRangeModelDetails::refTo(row));
3935 using Children = std::remove_reference_t<decltype(children)>;
3936
3937 if constexpr (QRangeModelDetails::is_any_of<Children, std::optional>())
3938 if constexpr (std::is_default_constructible<typename Children::value_type>()) {
3939 if (!children)
3940 children.emplace(range_type{});
3941 }
3942
3943 return QRangeModelDetails::pointerTo(std::forward<decltype(children)>(children));
3944 }
3945
3946 const range_type &childrenOf(const_row_ptr row) const
3947 {
3948 return row ? QRangeModelDetails::refTo(this->protocol().childRows(*row))
3949 : *this->m_data.model();
3950 }
3951
3952 range_type &childrenOf(row_ptr row)
3953 {
3954 return row ? QRangeModelDetails::refTo(this->protocol().childRows(*row))
3955 : *this->m_data.model();
3956 }
3957
3958 template <typename LessThan>
3959 void sortImplRecursive(range_type &range, row_ptr parentRow, const LessThan &lessThan)
3960 {
3961 for (auto &row : range) {
3962 decltype(auto) children = this->protocol().childRows(QRangeModelDetails::refTo(row));
3963 if (QRangeModelDetails::isValid(children)) {
3964 sortImplRecursive(QRangeModelDetails::refTo(children),
3965 QRangeModelDetails::pointerTo(row), lessThan);
3966 }
3967 }
3968 this->sortSubRange(range, parentRow, lessThan);
3969 }
3970
3971 template <typename LessThan>
3972 void sortImpl(const LessThan &lessThan)
3973 {
3974 sortImplRecursive(*this->m_data.model(), nullptr, lessThan);
3975 resetParentInChildren(this->m_data.model());
3976 }
3977
3978 void prunePersistentIndexList(QModelIndexList &list, row_ptr expectedParent)
3979 {
3980 erase_if(list, [expectedParent](const QModelIndex &index){
3981 return static_cast<row_ptr>(index.internalPointer()) != expectedParent;
3982 });
3983 }
3984
3985 void matchImplRecursive(const range_type &range, const_row_ptr parentPtr, int from, int to,
3986 int role, const QVariant &value, int hits, Qt::MatchFlags flags, int column,
3987 QModelIndexList &result) const
3988 {
3989 auto it = QRangeModelDetails::pos(range, from);
3990 auto end = QRangeModelDetails::adl_end(range);
3991
3992 const bool recurse = flags.testAnyFlag(Qt::MatchRecursive);
3993 const bool allHits = (hits == -1);
3994
3995 for (int r = from; it != end && r < to && (allHits || result.size() < hits); ++it, ++r) {
3996 const QModelIndex index = this->createIndex(r, column, parentPtr);
3997 if (this->matchRow(*it, index, role, value, flags))
3998 result.append(index);
3999
4000 if (recurse) {
4001 decltype(auto) children = this->protocol().childRows(QRangeModelDetails::refTo(*it));
4002
4003 if (QRangeModelDetails::isValid(children)) {
4004 matchImplRecursive(QRangeModelDetails::refTo(children),
4005 QRangeModelDetails::pointerTo(*it), 0,
4006 int(QRangeModelDetails::size(QRangeModelDetails::refTo(children))),
4007 role, value, hits, flags, column, result);
4008 }
4009 }
4010 }
4011 }
4012
4013 QModelIndexList matchImpl(const QModelIndex &start, int role, const QVariant &value, int hits,
4014 Qt::MatchFlags flags) const
4015 {
4016 QModelIndexList result;
4017 const bool wrap = flags.testAnyFlag(Qt::MatchWrap);
4018 const int column = start.column();
4019 const int from = start.row();
4020 const int to = this->rowCount(start.parent());
4021
4022 for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i) {
4023 const int fromRow = (i == 0) ? from : 0;
4024 const int toRow = (i == 0) ? to : from;
4025 matchImplRecursive(*this->m_data.model(), nullptr, fromRow, toRow,
4026 role, value, hits, flags, column, result);
4027 }
4028 return result;
4029 }
4030
4031 // tree models don't overwrite the data at index, but instead insert a
4032 // child item
4033 bool dropOnItem(const QMimeData *, const QModelIndex &)
4034 {
4035 return false;
4036 }
4037};
4038
4039// specialization for flat models without protocol
4040template <typename Range>
4043{
4046
4047 static constexpr bool is_mutable_impl = true;
4048
4049public:
4050 using range_type = typename Base::range_type;
4052 using row_type = typename Base::row_type;
4053 using row_ptr = typename Base::row_ptr;
4055 using row_traits = typename Base::row_traits;
4056 using row_features = typename Base::row_features;
4057
4058 explicit QGenericTableItemModelImpl(Range &&model, QRangeModel *itemModel)
4059 : Base(std::forward<Range>(model), {}, itemModel)
4060 {}
4061
4062protected:
4063 QModelIndex indexImpl(int row, int column, const QModelIndex &) const
4064 {
4065 if constexpr (Base::dynamicColumns()) {
4066 if (column < int(Base::size(*QRangeModelDetails::pos(*this->m_data.model(), row))))
4067 return this->createIndex(row, column);
4068#ifndef QT_NO_DEBUG
4069 // if we got here, then column < columnCount(), but this row is too short
4070 qCritical("QRangeModel: Column-range at row %d is not large enough!", row);
4071#endif
4072 return {};
4073 } else {
4074 return this->createIndex(row, column);
4075 }
4076 }
4077
4078 QModelIndex parentImpl(const QModelIndex &) const
4079 {
4080 return {};
4081 }
4082
4083 int rowCountImpl(const QModelIndex &parent) const
4084 {
4085 if (parent.isValid())
4086 return 0;
4087 return int(Base::size(*this->m_data.model()));
4088 }
4089
4090 int columnCountImpl(const QModelIndex &parent) const
4091 {
4092 if (parent.isValid())
4093 return 0;
4094
4095 // in a table, all rows have the same number of columns (as the first row)
4096 if constexpr (Base::dynamicColumns()) {
4097 return int(Base::size(*this->m_data.model()) == 0
4098 ? 0
4099 : Base::size(*QRangeModelDetails::adl_begin(*this->m_data.model())));
4100 } else {
4101 return Base::fixedColumnCount();
4102 }
4103 }
4104
4105 static constexpr Qt::ItemFlags defaultFlags()
4106 {
4107 return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemNeverHasChildren;
4108 }
4109
4110 static constexpr bool canInsertRowsImpl()
4111 {
4112 return Base::dynamicRows() && range_features::has_insert;
4113 }
4114
4115 static constexpr bool canRemoveRowsImpl()
4116 {
4117 return Base::dynamicRows() && range_features::has_erase;
4118 }
4119
4120 static constexpr bool canMoveColumns(const QModelIndex &source, const QModelIndex &destination)
4121 {
4122 return !source.isValid() && !destination.isValid();
4123 }
4124
4125 static constexpr bool canMoveRows(const QModelIndex &source, const QModelIndex &destination)
4126 {
4127 return !source.isValid() && !destination.isValid();
4128 }
4129
4130 constexpr bool moveRowsAcross(const QModelIndex &, int , int,
4131 const QModelIndex &, int) noexcept
4132 {
4133 // table/flat model: can't move rows between different parents
4134 return false;
4135 }
4136
4137 auto makeEmptyRow(typename Base::row_ptr)
4138 {
4139 row_type empty_row = this->protocol().newRow();
4140
4141 // dynamically sized rows all have to have the same column count
4142 if constexpr (Base::dynamicColumns() && row_features::has_resize) {
4143 if (QRangeModelDetails::isValid(empty_row))
4144 QRangeModelDetails::refTo(empty_row).resize(this->columnCount({}));
4145 }
4146
4147 return empty_row;
4148 }
4149
4150 template <typename It, typename Sentinel>
4151 void deleteRemovedRows(It &&begin, Sentinel &&end)
4152 {
4153 if constexpr (Base::protocol_traits::has_deleteRow) {
4154 for (auto it = begin; it != end; ++it)
4155 this->protocol().deleteRow(std::move(*it));
4156 }
4157 }
4158
4159 decltype(auto) rowDataImpl(const QModelIndex &index) const
4160 {
4161 Q_ASSERT(q20::cmp_less(index.row(), Base::size(*this->m_data.model())));
4162 return *QRangeModelDetails::pos(*this->m_data.model(), index.row());
4163 }
4164
4165 decltype(auto) rowDataImpl(const QModelIndex &index)
4166 {
4167 Q_ASSERT(q20::cmp_less(index.row(), Base::size(*this->m_data.model())));
4168 return *QRangeModelDetails::pos(*this->m_data.model(), index.row());
4169 }
4170
4171 const range_type *childRangeImpl(const QModelIndex &) const
4172 {
4173 return nullptr;
4174 }
4175
4176 range_type *childRangeImpl(const QModelIndex &)
4177 {
4178 return nullptr;
4179 }
4180
4181 const range_type &childrenOf(const_row_ptr row) const
4182 {
4183 Q_ASSERT(!row);
4184 return *this->m_data.model();
4185 }
4186
4188 {
4189 Q_ASSERT(!row);
4190 return *this->m_data.model();
4191 }
4192
4193 void resetParentInChildren(range_type *)
4194 {
4195 }
4196
4198 {
4199 bool result = true;
4200 int rowIndex = 0;
4201 for (const auto &row : *this->m_data.model()) {
4202 result &= this->autoConnectPropertiesInRow(row, rowIndex, {});
4203 ++rowIndex;
4204 }
4205 return result;
4206 }
4207
4208 template <typename LessThan>
4209 void sortImpl(const LessThan &lessThan)
4210 {
4211 this->sortSubRange(*this->m_data.model(), nullptr, lessThan);
4212 }
4213
4214 void prunePersistentIndexList(QModelIndexList &, typename Base::row_ptr) {}
4215
4216 QModelIndexList matchImpl(const QModelIndex &start, int role, const QVariant &value,
4217 int hits, Qt::MatchFlags flags) const
4218 {
4219 QModelIndexList result;
4220 const bool wrap = flags.testAnyFlag(Qt::MatchWrap);
4221 const bool allHits = (hits == -1);
4222 const int column = start.column();
4223 int from = start.row();
4224 int to = this->rowCount({});
4225 decltype(auto) siblings = *this->m_data.model();
4226
4227 for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i) {
4228 auto it = QRangeModelDetails::pos(siblings, from);
4229 auto end = QRangeModelDetails::adl_end(siblings);
4230 for (int r = from; it != end && r < to && (allHits || result.size() < hits);
4231 ++it, ++r) {
4232 if (!QRangeModelDetails::isValid(*it))
4233 continue;
4234 const QModelIndex index = this->createIndex(r, column, nullptr);
4235 if (this->matchRow(*it, index, role, value, flags))
4236 result.append(index);
4237 }
4238 from = 0;
4239 to = start.row();
4240 }
4241
4242 return result;
4243 }
4244
4245 // flat models can overwrite data of the dropped-on item
4246 bool dropOnItem(const QMimeData *data, const QModelIndex &index)
4247 {
4248 return this->dropDataOnItem(data, index);
4249 }
4250};
4251
4252QT_END_NAMESPACE
4253
4254#endif // Q_QDOC
4255
4256#endif // QRANGEMODEL_IMPL_H
QModelIndex parentImpl(const QModelIndex &) const
static constexpr bool canMoveRows(const QModelIndex &source, const QModelIndex &destination)
void deleteRemovedRows(It &&begin, Sentinel &&end)
QModelIndexList matchImpl(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const
const range_type & childrenOf(const_row_ptr row) const
static constexpr bool canRemoveRowsImpl()
bool dropOnItem(const QMimeData *data, const QModelIndex &index)
QGenericTableItemModelImpl(Range &&model, QRangeModel *itemModel)
range_type * childRangeImpl(const QModelIndex &)
int columnCountImpl(const QModelIndex &parent) const
constexpr bool moveRowsAcross(const QModelIndex &, int, int, const QModelIndex &, int) noexcept
decltype(auto) rowDataImpl(const QModelIndex &index) const
static constexpr bool canInsertRowsImpl()
const range_type * childRangeImpl(const QModelIndex &) const
int rowCountImpl(const QModelIndex &parent) const
void resetParentInChildren(range_type *)
void prunePersistentIndexList(QModelIndexList &, typename Base::row_ptr)
static constexpr bool canMoveColumns(const QModelIndex &source, const QModelIndex &destination)
decltype(auto) rowDataImpl(const QModelIndex &index)
QModelIndex indexImpl(int row, int column, const QModelIndex &) const
range_type & childrenOf(row_ptr row)
static constexpr Qt::ItemFlags defaultFlags()
void sortImpl(const LessThan &lessThan)
auto makeEmptyRow(typename Base::row_ptr)
static constexpr bool canMoveColumns(const QModelIndex &, const QModelIndex &)
void matchImplRecursive(const range_type &range, const_row_ptr parentPtr, int from, int to, int role, const QVariant &value, int hits, Qt::MatchFlags flags, int column, QModelIndexList &result) const
bool dropOnItem(const QMimeData *, const QModelIndex &)
QModelIndexList matchImpl(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const
auto makeEmptyRow(row_ptr parentRow)
void setParentRow(range_type &children, row_ptr parent)
range_type * childRangeImpl(const QModelIndex &index)
bool moveRowsAcross(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destParent, int destRow)
void resetParentInChildren(range_type *children)
int rowCountImpl(const QModelIndex &parent) const
range_type & childrenOf(row_ptr row)
static constexpr bool canRemoveRowsImpl()
void resetParentInChildrenRecursive(range_type *children, int pmiFromColumn, int pmiToColumn)
int columnCountImpl(const QModelIndex &) const
static constexpr bool canMoveRows(const QModelIndex &, const QModelIndex &)
const range_type & childrenOf(const_row_ptr row) const
decltype(auto) rowDataImpl(const QModelIndex &index)
QGenericTreeItemModelImpl(Range &&model, Protocol &&p, QRangeModel *itemModel)
void prunePersistentIndexList(QModelIndexList &list, row_ptr expectedParent)
bool autoConnectPropertiesRange(const range_type &range, const QModelIndex &parent) const
QModelIndex indexImpl(int row, int column, const QModelIndex &parent) const
void deleteRemovedRows(It &&begin, Sentinel &&end)
bool autoConnectProperties(const QModelIndex &parent) const
void sortImplRecursive(range_type &range, row_ptr parentRow, const LessThan &lessThan)
const range_type * childRangeImpl(const QModelIndex &index) const
static constexpr bool canInsertRowsImpl()
decltype(auto) rowDataImpl(const QModelIndex &index) const
void deleteRemovedRows(range_type &range)
static constexpr Qt::ItemFlags defaultFlags()
void sortImpl(const LessThan &lessThan)
QModelIndex parentImpl(const QModelIndex &child) const
const QAbstractItemModel & itemModel() const
void beginInsertRows(const QModelIndex &parent, int start, int count)
void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
bool beginMoveColumns(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destParent, int destRow)
QStringList mimeTypes() const
bool setItemData(const QModelIndex &index, const QMap< int, QVariant > &data)
QMap< int, QVariant > itemData(const QModelIndex &index) const
bool insertRows(int row, int count, const QModelIndex &parent)
Qt::DropActions adjustSupportedDropActions(Qt::DropActions dropActions)
Qt::ItemFlags flags(const QModelIndex &index) const
bool beginMoveRows(const QModelIndex &sourceParent, int sourceFirst, int sourceLast, const QModelIndex &destParent, int destRow)
void beginRemoveRows(const QModelIndex &parent, int start, int count)
bool clearItemData(const QModelIndex &index)
QVariant data(const QModelIndex &index, int role) const
QRangeModelImplBase(QRangeModel *itemModel)
QModelIndexList persistentIndexList() const
bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const
int columnCount(const QModelIndex &parent) const
static Q_CORE_EXPORT bool connectProperties(const QModelIndex &index, const QObject *item, QRangeModelDetails::AutoConnectContext *context, const QHash< int, QMetaProperty > &properties)
QModelIndex sibling(int row, int column, const QModelIndex &index) const
void beginInsertColumns(const QModelIndex &parent, int start, int count)
bool insertColumns(int column, int count, const QModelIndex &parent)
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
void sort(int column, Qt::SortOrder order)
bool removeRows(int row, int count, const QModelIndex &parent)
Qt::DropActions adjustSupportedDragActions(Qt::DropActions dragActions)
static Q_CORE_EXPORT bool matchValue(const QString &itemData, const QVariant &value, Qt::MatchFlags flags)
QModelIndex parent(const QModelIndex &child) const
void changePersistentIndex(const QModelIndex &from, const QModelIndex &to)
QAbstractItemModel & itemModel()
QModelIndex createIndex(int row, int column, const void *ptr=nullptr) const
QHash< int, QByteArray > roleNames() const
void interfaceVersion(int &version) const
bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destParent, int destColumn)
bool setData(const QModelIndex &index, const QVariant &data, int role)
void dataChanged(const QModelIndex &from, const QModelIndex &to, const QList< int > &roles)
QVariant headerData(int section, Qt::Orientation orientation, int role) const
static Q_CORE_EXPORT bool connectPropertiesConst(const QModelIndex &index, const QObject *item, QRangeModelDetails::AutoConnectContext *context, const QHash< int, QMetaProperty > &properties)
static Qt::partial_ordering compareData(const QVariant &lhs, const QVariant &rhs, const QCollator *collator)
AutoConnectPolicy autoConnectPolicy() const
bool removeColumns(int column, int count, const QModelIndex &parent)
Q_CORE_EXPORT bool dropDataOnItem(const QMimeData *data, const QModelIndex &index)
static Q_CORE_EXPORT bool connectPropertyConst(const QModelIndex &index, const QObject *item, QRangeModelDetails::AutoConnectContext *context, int role, const QMetaProperty &property)
std::tuple< typename C::Destroy, typename C::InvalidateCaches, typename C::SetHeaderData, typename C::SetData, typename C::SetItemData, typename C::ClearItemData, typename C::InsertColumns, typename C::RemoveColumns, typename C::MoveColumns, typename C::InsertRows, typename C::RemoveRows, typename C::MoveRows, typename C::Index, typename C::Parent, typename C::Sibling, typename C::RowCount, typename C::ColumnCount, typename C::Flags, typename C::HeaderData, typename C::Data, typename C::ItemData, typename C::RoleNames, typename C::MultiData, typename C::SetAutoConnectPolicy, typename C::InterfaceVersion, typename C::Sort, typename C::Match, typename C::AdjustSupportedDragActions, typename C::AdjustSupportedDropActions, typename C::MimeTypes, typename C::CanDropMimeData, typename C::DropMimeData, typename C::MimeData > MethodTemplates
QModelIndex index(int row, int column, const QModelIndex &parent) const
QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const
QMimeData * mimeData(const QModelIndexList &indexes) const
bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &data, int role)
int rowCount(const QModelIndex &parent) const
Q_CORE_EXPORT int sortRole() const
static Q_CORE_EXPORT bool connectProperty(const QModelIndex &index, const QObject *item, QRangeModelDetails::AutoConnectContext *context, int role, const QMetaProperty &property)
void beginRemoveColumns(const QModelIndex &parent, int start, int count)
bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destParent, int destRow)
bool removeRows(int row, int count, const QModelIndex &parent={})
static QVariant readProperty(const QMetaProperty &prop, ItemType *gadget)
QHash< int, QByteArray > roleNames() const
row_reference rowData(const QModelIndex &index)
static constexpr bool dynamicRows()
static QVariant read(const Value &value)
const range_type * childRange(const QModelIndex &index) const
bool moveColumns(const QModelIndex &sourceParent, int sourceColumn, int count, const QModelIndex &destParent, int destColumn)
auto maybeBlockDataChangedDispatch()
static constexpr bool has_metaobject
QMetaProperty roleProperty(int role) const
int columnCount(const QModelIndex &parent) const
bool writeRole(int role, ItemType &&gadget, const QVariant &data)
static bool write(Target *target, const QVariant &value)
void connectPropertyOnRead(const QModelIndex &index, int role, const QObject *gadget, const QMetaProperty &prop) const
Qt::ItemFlags flags(const QModelIndex &index) const
bool insertColumns(int column, int count, const QModelIndex &parent)
bool doDropMimeData(std::vector< QRangeModelDetails::DroppedEntry< Entry > > &droppedEntries, DropOperation dropOperation, int row, int column, const QModelIndex &target)
QVariant data(const QModelIndex &index, int role) const
QModelIndexList match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const
QVariant headerData(int section, Qt::Orientation orientation, int role) const
static constexpr bool isRangeModelRole(int role)
bool clearItemData(const QModelIndex &index)
void multiData(const QModelIndex &index, QModelRoleDataSpan roleDataSpan) const
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &target)
static constexpr int fixedColumnCount()
const protocol_type & protocol() const
static bool resetProperty(int property, ItemType &&object)
QModelIndex sibling(int row, int column, const QModelIndex &index) const
static bool writeProperty(int property, ItemType &&gadget, const QVariant &data)
bool setItemData(const QModelIndex &index, const QMap< int, QVariant > &data)
bool insertRows(int row, int count, const QModelIndex &parent)
static constexpr bool canInsertRows()
void interfaceVersion(int &versionNumber) const
static bool writeProperty(const QMetaProperty &prop, ItemType *gadget, const QVariant &data)
QVariant readProperty(const QModelIndex &index, ItemType *gadget) const
void sort(int column, Qt::SortOrder order)
static constexpr int size(const C &c)
const_row_reference rowData(const QModelIndex &index) const
bool writeAt(const QModelIndex &index, F &&writer)
static constexpr bool one_dimensional_range
static constexpr bool rows_are_raw_pointers
bool setHeaderData(int, Qt::Orientation, const QVariant &, int)
bool removeColumns(int column, int count, const QModelIndex &parent)
static constexpr bool isMutable()
bool setData(const QModelIndex &index, const QVariant &data, int role)
QModelIndex parent(const QModelIndex &child) const
static QVariant read(Value *value)
static bool write(Target &target, const QVariant &value)
bool writeRole(int role, ItemType *gadget, const QVariant &data)
QVariant readRole(const QModelIndex &index, int role, const ItemType &gadget) const
Qt::DropActions adjustSupportedDragActions(Qt::DropActions dragActions)
QRangeModelImpl< Structure, Range, Protocol > Self
bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &target) const
static constexpr bool canRemoveRows()
static constexpr int static_column_count
QVariant readProperty(const QModelIndex &index, const ItemType &gadget) const
protocol_type & protocol()
int rowCount(const QModelIndex &parent) const
static constexpr bool rows_are_owning_or_raw_pointers
QModelIndex index(int row, int column, const QModelIndex &parent) const
static constexpr int static_row_count
static bool writeProperty(int property, ItemType *gadget, const QVariant &data)
QRangeModelImpl(Range &&model, Protocol &&protocol, QRangeModel *itemModel)
void sortSubRange(range_type &range, row_ptr expectedParent, const LessThan &lessThan)
const Structure & that() const
static constexpr bool isPrimaryRole(int role)
void updateTarget(LHS *org, RHS &&copy) noexcept
static constexpr bool itemsAreQObjects
static constexpr bool dynamicColumns()
range_type * childRange(const QModelIndex &index)
bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destParent, int destRow)
QStringList mimeTypes() const
QVariant readRole(const QModelIndex &index, int role, ItemType *gadget) const
static bool resetProperty(int property, ItemType *object)
bool autoConnectPropertiesInRow(const row_type &row, int rowIndex, const QModelIndex &parent) const
bool readAt(const QModelIndex &index, F &&reader) const
static constexpr bool rowsAreQObjects
bool doInsertColumns(int column, int count, const QModelIndex &parent, InsertFn insertFn)
void updateTarget(LHS &org, RHS &&copy) noexcept
QMimeData * mimeData(const QModelIndexList &indexes) const
Qt::DropActions adjustSupportedDropActions(Qt::DropActions dropActions)
QMap< int, QVariant > itemData(const QModelIndex &index) const
void clearConnectionInRow(const row_type &row, int rowIndex, const QModelIndex &parent) const
bool doInsertRows(int row, int count, const QModelIndex &parent, InsertFn &&insertFn)
bool matchRow(const_row_reference row, const QModelIndex &index, int role, const QVariant &value, Qt::MatchFlags flags) const
decltype(QRangeModelRowOptions< row_type >::mimeTypes()) hasMimeTypes_test
static auto adl_end(C &&c) -> decltype(end(QRangeModelDetails::refTo(std::forward< C >(c))))
decltype(QRangeModelRowOptions< row_type >::flags(std::declval< const row_type & >())) hasRowFlags_test
static constexpr bool hasMimeDataRowSpan
static constexpr bool hasMimeTypes
static constexpr bool has_metaobject_v
static constexpr bool is_range_v
static constexpr bool array_like_v
static constexpr bool hasMimeDataIndexList
static void rotate(C &c, int src, int count, int dst)
static constexpr bool hasDropMimeData
static constexpr bool tuple_like_v
typename QRangeModelDetails::wrapped_helper< T >::type wrapped_t
auto value(It &&it) -> decltype(it.value())
std::conjunction< std::is_swappable< decltype(*std::declval< It >())>, std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits< It >::iterator_category > > test_rotate
auto key(It &&it) -> decltype(it.key())
static constexpr bool hasDropMimeDataFull
static constexpr int static_size_v
static constexpr bool isValid(const T &t) noexcept
static auto pos(C &&c, int i)
static constexpr bool hasHeaderData
static constexpr bool hasCanDropMimeData
static decltype(auto) refTo(T &&t)
static constexpr bool hasRowFlags
static auto pointerTo(T &&t)
static constexpr bool hasCanDropMimeDataFull
static auto adl_begin(C &&c) -> decltype(begin(QRangeModelDetails::refTo(std::forward< C >(c))))
static constexpr bool is_multi_role_v
friend bool operator==(const Connection &lhs, const Connection &rhs) noexcept
friend size_t qHash(const Connection &c, size_t seed) noexcept
auto setParentRow(R &row, R *parent) -> decltype(row.setParentRow(parent))
auto childRows(R &row) -> decltype(row.childRows())
auto childRows(const R &row) const -> decltype(row.childRows())
auto parentRow(const R &row) const -> decltype(row.parentRow())
friend bool operator==(const Cell &lhs, const Cell &rhs) noexcept
const QModelIndex & index() const
friend decltype(auto) get(const MimeDataEntry &entry)
const wrapped_entry & entry() const
QHash< int, QMetaProperty > properties
static constexpr bool cachesProperties
std::remove_const_t< ModelStorage > m_model
static constexpr bool hasCanDropMimeDataFull
static constexpr bool hasMimeData
decltype(Access::flags(std::declval< const Test & >())) hasFlags_test
static constexpr bool hasReadRole
static constexpr bool hasWriteRole
static constexpr bool hasDropMimeData
decltype(Access::mimeTypes()) hasMimeTypes_test
static constexpr bool hasMimeTypes
static constexpr bool hasDropMimeDataFull
static constexpr bool hasCanDropMimeData
static QHash< int, QByteArray > roleNames(That *)
static constexpr bool has_mutable_childRows
static constexpr bool has_insert_range
static constexpr int fixed_size()
static bool for_each_element(const T &row, const QModelIndex &firstIndex, Fn &&fn)
static bool for_element_at(C &&container, std::size_t idx, Fn &&fn)
static constexpr bool hasMetaObject
decltype(std::declval< C & >().sort(std::declval< LessThan && >())) sortMember_test
static constexpr bool hasCollatedCompare
const QRangeModelImpl *const that
const QCollator *const collator
auto compare(const Item &lhs, const Item &rhs) const
static constexpr bool hasSortMember
auto operator()(const Item &lhs, const Item &rhs) const
Compare(const QRangeModelImpl *impl, int column, Qt::SortOrder order)
const Qt::SortOrder m_order
static std::optional< bool > compareInvalid(const Item &lhs, const Item &rhs)
std::input_iterator_tag iterator_category
friend bool operator==(const EmptyRowGenerator &lhs, const EmptyRowGenerator &rhs) noexcept
friend bool operator!=(const EmptyRowGenerator &lhs, const EmptyRowGenerator &rhs) noexcept
bool operator()(const value_type &value) const
const QRangeModelImpl *const that
std::bidirectional_iterator_tag iterator_category
bool operator!=(const MimeDataItemIterator &other) const
MimeDataItemIterator operator-(difference_type n) const
bool operator==(const MimeDataItemIterator &other) const
MimeDataRowIterator operator-(difference_type n) const
bool operator!=(const MimeDataRowIterator &other) const
bool operator==(const MimeDataRowIterator &other) const
MimeDataRowIterator(base_iterator it, base_iterator begin, base_iterator end, const QRangeModelImpl *model)
std::bidirectional_iterator_tag iterator_category
friend constexpr bool operator<(unordered, QtPrivate::CompareAgainstLiteralZero) noexcept
friend constexpr bool operator>(unordered, QtPrivate::CompareAgainstLiteralZero) noexcept