Skip to content

card_view

AYCardView component module.

A flow-layout card view built on QAbstractItemView that displays AYEntityCard widgets using the same PaginatedTableModel as AYTableView. Supports collapsible grouping in tree mode.

AYCardView

Bases: QAbstractItemView

AYON-styled card view that displays AYEntityCard widgets in a flow layout.

Uses the same PaginatedTableModel as AYTableView. In tree mode, groups are rendered as collapsible painted headers with cards flowing beneath each group.

Parameters:

Name Type Description Default
parent QWidget | None

Optional parent widget.

None
variant AYCardViewVariants

Visual style variant.

Default
card_width int

Initial card width in pixels.

200
card_spacing int

Horizontal and vertical spacing between cards.

8
card_data_mapper Callable[[dict[str, Any]], dict[str, Any]] | None

Callable mapping row_data dict to AYEntityCard keyword arguments. If None, no cards are created.

None
group_header_height int

Height of group header bars in tree mode.

36
Source code in client/ayon_ui_qt/components/card_view.py
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
class AYCardView(QAbstractItemView):
    """AYON-styled card view that displays AYEntityCard widgets in a flow
    layout.

    Uses the same PaginatedTableModel as AYTableView. In tree mode, groups
    are rendered as collapsible painted headers with cards flowing beneath
    each group.

    Args:
        parent: Optional parent widget.
        variant: Visual style variant.
        card_width: Initial card width in pixels.
        card_spacing: Horizontal and vertical spacing between cards.
        card_data_mapper: Callable mapping row_data dict to AYEntityCard
            keyword arguments. If None, no cards are created.
        group_header_height: Height of group header bars in tree mode.
    """

    Variants = AYCardViewVariants
    selection_changed = Signal(QItemSelection, QItemSelection)
    card_activated = Signal(QModelIndex)

    def __init__(
        self,
        parent: QWidget | None = None,
        variant: AYCardViewVariants = AYCardViewVariants.Default,
        card_width: int = 200,
        card_spacing: int = 8,
        card_data_mapper: Callable[[dict[str, Any]], dict[str, Any]]
        | None = None,
        group_header_height: int = 36,
    ) -> None:
        self._variant_str: str = variant.value
        super().__init__(parent)

        # FIXME: this is crashing
        # style = get_ayon_style()
        # self.setStyle(style)

        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WidgetAttribute.WA_Hover, True)
        self.setMouseTracking(True)
        self.viewport().setMouseTracking(True)
        self.viewport().setAttribute(
            Qt.WidgetAttribute.WA_TranslucentBackground, False
        )
        self._sync_viewport_palette()

        self._card_width: int = card_width
        self._card_spacing: int = card_spacing
        self._card_data_mapper: (
            Callable[[dict[str, Any]], dict[str, Any]] | None
        ) = card_data_mapper
        self._group_header_height: int = group_header_height
        self.scroll_step = max(1, int(self._card_width / CARD_RATIO * 0.1))

        vsb = AYScrollBar(Qt.Orientation.Vertical, self)
        self.setVerticalScrollBar(vsb)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        self.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOff
        )
        vsb.valueChanged.connect(self._on_scroll)

        self._delegate = _CardDelegate(
            card_width=self._card_width,
            card_data_mapper=card_data_mapper or (lambda r: {}),
            parent=self.viewport(),
        )
        self.setItemDelegate(self._delegate)

        self._active_editor_pmis: set[QPersistentModelIndex] = set()
        self._editor_sync_timer = QtCore.QTimer(self)
        self._editor_sync_timer.setSingleShot(True)
        self._editor_sync_timer.setInterval(0)
        self._editor_sync_timer.timeout.connect(self._sync_viewport_editors)

        self._model_connections: list[
            tuple[Any, QtCore.QMetaObject.Connection]
        ] = []

        self._collapsed_groups: set[str] = set()

        self._tree_layout: list[_GroupLayout] = []
        self._flat_layout: list[_LayoutItem] = []
        self._total_content_height: int = 0
        self._is_tree_mode: bool = False

        self._hovered_pmi: QPersistentModelIndex | None = None

        self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.setFrameShape(QAbstractItemView.Shape.NoFrame)

    def set_card_width(self, width: int) -> None:
        self._card_width = width
        self.scroll_step = max(1, int(self._card_width / CARD_RATIO * 0.1))
        self._delegate.set_card_width(width)
        for pmi in self._active_editor_pmis:
            if not pmi.isValid():
                continue
            editor = self.indexWidget(QModelIndex(pmi))  # type: ignore
            if isinstance(editor, AYEntityCard):
                editor.resize_to_width(width)
        self._calculate_layout()
        self._sync_viewport_editors()

    def _sync_viewport_palette(self) -> None:
        style = get_ayon_style()
        tbl_style = style.model.get_style("AYTableView", self._variant_str)
        tbl_style.set_context(self)
        bg = QColor(tbl_style.get("background-color", "#252a31"))
        p = self.viewport().palette()
        p.setColor(QPalette.ColorRole.Base, bg)
        p.setColor(QPalette.ColorRole.Window, bg)
        self.viewport().setPalette(p)

    def _source_model(self) -> QtCore.QAbstractItemModel | None:
        model = self.model()
        if isinstance(model, QSortFilterProxyModel):
            return model.sourceModel()
        return model

    def setModel(self, model: QtCore.QAbstractItemModel | None) -> None:
        for obj, conn in self._model_connections:
            try:
                obj.disconnect(conn)
            except (RuntimeError, TypeError):
                pass
        self._model_connections.clear()

        self._active_editor_pmis.clear()
        self._editor_sync_timer.stop()

        super().setModel(model)

        if model is None:
            return

        conn = model.rowsInserted.connect(self._on_rows_inserted)
        if conn is not None:
            self._model_connections.append((model, conn))

        conn_reset = model.modelReset.connect(self._on_model_reset)
        if conn_reset is not None:
            self._model_connections.append((model, conn_reset))

        conn_dc = model.dataChanged.connect(self._on_data_changed)
        if conn_dc is not None:
            self._model_connections.append((model, conn_dc))

        conn_layout = model.layoutChanged.connect(self._on_layout_changed)
        if conn_layout is not None:
            self._model_connections.append((model, conn_layout))

        conn_removed = model.rowsRemoved.connect(self._on_rows_removed)
        if conn_removed is not None:
            self._model_connections.append((model, conn_removed))

        source: Any = model
        if isinstance(model, QSortFilterProxyModel):
            source = model.sourceModel()
        if isinstance(source, PaginatedTableModel):
            conn2 = source.tree_mode_changed.connect(
                self._on_tree_mode_changed
            )
            if conn2 is not None:
                self._model_connections.append((source, conn2))
            self._on_tree_mode_changed(source._tree_mode)

        self._schedule_layout_update()

    def _on_tree_mode_changed(self, tree_mode: bool) -> None:
        self._is_tree_mode = tree_mode
        self._schedule_layout_update()

    def _on_rows_inserted(
        self, parent: QModelIndex, first: int, last: int
    ) -> None:
        self._schedule_layout_update()

    def _on_model_reset(self) -> None:
        self._active_editor_pmis.clear()
        self._schedule_layout_update()

    def _on_data_changed(
        self,
        top_left: QModelIndex,
        bottom_right: QModelIndex,
        roles: list[int],
    ) -> None:
        self.viewport().update()

    def _on_layout_changed(self) -> None:
        """Handle layoutChanged emitted by the proxy on filter/sort changes.

        Closes all currently-open persistent editors whose
        ``QPersistentModelIndex`` is still valid (i.e. rows that survived
        the filter but may have been renumbered), then hides any orphaned
        ``AYEntityCard`` widgets whose PMIs became invalid (rows that were
        filtered out — ``closePersistentEditor`` is a no-op for invalid
        indices, so the widgets must be hidden manually).  Finally clears
        the tracking set and schedules a full layout rebuild so that only
        the rows that pass the new filter get fresh editors.
        """
        for pmi in self._active_editor_pmis:
            if pmi.isValid():
                self.closePersistentEditor(QModelIndex(pmi))  # type: ignore
        for child in self.viewport().children():
            if isinstance(child, AYEntityCard):
                child.hide()
        self._active_editor_pmis.clear()
        self._schedule_layout_update()

    def _on_rows_removed(
        self,
        parent: QModelIndex,
        first: int,
        last: int,
    ) -> None:
        """Schedule a layout update when rows are removed from the model.

        Args:
            parent: Parent index of the removed rows.
            first: First removed row index.
            last: Last removed row index (inclusive).
        """
        self._schedule_layout_update()

    def _on_scroll(self) -> None:
        self._reposition_visible_editors()
        self.viewport().update()
        self._schedule_editor_sync()

    def _schedule_layout_update(self) -> None:
        if not self._editor_sync_timer.isActive():
            self._editor_sync_timer.start()

    def _schedule_editor_sync(self) -> None:
        if not self._editor_sync_timer.isActive():
            self._editor_sync_timer.start()

    def _calculate_layout(self) -> None:
        model = self.model()
        self._tree_layout = []
        self._flat_layout = []
        self._total_content_height = 0

        if model is None or model.rowCount() == 0:
            self.updateGeometries()
            return

        vp_width = self.viewport().width()
        spacing = self._card_spacing
        card_w = self._card_width
        card_h = int(card_w / CARD_RATIO)
        margin = spacing

        if self._is_tree_mode:
            self._calculate_tree_layout(
                model, vp_width, margin, spacing, card_w, card_h
            )
        else:
            self._calculate_flat_layout(
                model, vp_width, margin, spacing, card_w, card_h
            )

        self.updateGeometries()

    def _flow_items(
        self,
        model: QtCore.QAbstractItemModel,
        parent_index: QModelIndex,
        start_y: int,
        vp_width: int,
        margin: int,
        spacing: int,
        card_w: int,
        card_h: int,
    ) -> tuple[list[_LayoutItem], int]:
        items: list[_LayoutItem] = []
        x = margin
        y = start_y
        line_height = 0
        row_count = model.rowCount(parent_index)

        for row in range(row_count):
            idx = model.index(row, 0, parent_index)
            if not idx.isValid():
                continue
            next_x = x + card_w + spacing
            if next_x - spacing > vp_width - margin and line_height > 0:
                x = margin
                y = y + line_height + spacing
                next_x = x + card_w + spacing
                line_height = 0
            rect = QRect(x, y, card_w, card_h)
            pmi = QPersistentModelIndex(idx)
            items.append(_LayoutItem(index=pmi, rect=rect))
            x = next_x
            line_height = max(line_height, card_h)

        end_y = y + line_height if line_height > 0 else start_y
        return items, end_y

    def _calculate_flat_layout(
        self,
        model: QtCore.QAbstractItemModel,
        vp_width: int,
        margin: int,
        spacing: int,
        card_w: int,
        card_h: int,
    ) -> None:
        items, end_y = self._flow_items(
            model,
            QModelIndex(),
            margin,
            vp_width,
            margin,
            spacing,
            card_w,
            card_h,
        )
        self._flat_layout = items
        self._total_content_height = end_y + margin

    def _calculate_tree_layout(
        self,
        model: QtCore.QAbstractItemModel,
        vp_width: int,
        margin: int,
        spacing: int,
        card_w: int,
        card_h: int,
    ) -> None:
        gh = self._group_header_height
        y = margin
        group_count = model.rowCount(QModelIndex())

        for g in range(group_count):
            group_idx = model.index(g, 0, QModelIndex())
            if not group_idx.isValid():
                continue

            node = None
            if isinstance(model, QSortFilterProxyModel):
                src_idx = model.mapToSource(group_idx)
                node = src_idx.internalPointer()
            else:
                node = group_idx.internalPointer()

            node_id = node.node_id if node is not None else str(g)
            label = group_idx.data(Qt.ItemDataRole.DisplayRole) or ""

            # DecorationRole / ForegroundRole data lives on the tree-position
            # column (e.g. "product/version"), NOT on column 0 ("thumb").
            # Resolve the right column from the source model when possible.
            src_model = self._source_model()
            tree_col = (
                src_model.tree_position
                if isinstance(src_model, PaginatedTableModel)
                else 0
            )
            meta_idx = (
                model.index(g, tree_col, QModelIndex())
                if tree_col != 0
                else group_idx
            )
            label_color = meta_idx.data(Qt.ItemDataRole.ForegroundRole)
            label_icon = meta_idx.data(Qt.ItemDataRole.DecorationRole)
            child_count = model.rowCount(group_idx)

            header_rect = QRect(0, y, vp_width, gh)
            y += gh + spacing

            collapsed = node_id in self._collapsed_groups

            if not collapsed:
                items, end_y = self._flow_items(
                    model,
                    group_idx,
                    y,
                    vp_width,
                    margin,
                    spacing,
                    card_w,
                    card_h,
                )
                y = end_y + spacing
            else:
                items = []

            self._tree_layout.append(
                _GroupLayout(
                    node_id=node_id,
                    label=label,
                    child_count=child_count,
                    header_rect=header_rect,
                    collapsed=collapsed,
                    label_color=label_color,
                    label_icon=label_icon,
                    items=items,
                    parent_index=QPersistentModelIndex(group_idx),
                )
            )

        self._total_content_height = y + margin

    def _all_layout_items(self) -> list[_LayoutItem]:
        if self._is_tree_mode:
            result = []
            for g in self._tree_layout:
                result.extend(g.items)
            return result
        return self._flat_layout

    def _rect_for_index(
        self, index: QModelIndex | QPersistentModelIndex
    ) -> QRect | None:
        pmi = QPersistentModelIndex(index)
        for item in self._all_layout_items():
            if item.index == pmi:
                return item.rect
        return None

    def _visible_rect(self, content_rect: QRect) -> QRect:
        offset = self.verticalOffset()
        return content_rect.translated(0, -offset)

    def horizontalOffset(self) -> int:
        return 0

    def verticalOffset(self) -> int:
        return self.verticalScrollBar().value()

    def visualRect(self, index: QModelIndex | QPersistentModelIndex) -> QRect:
        if not index.isValid():
            return QRect()
        content_rect = self._rect_for_index(index)
        if content_rect is None:
            return QRect()
        return self._visible_rect(content_rect)

    def scrollTo(
        self,
        index: QModelIndex | QPersistentModelIndex,
        hint: QAbstractItemView.ScrollHint = QAbstractItemView.ScrollHint.EnsureVisible,
    ) -> None:
        if not index.isValid():
            return
        content_rect = self._rect_for_index(index)
        if content_rect is None:
            return

        vsb = self.verticalScrollBar()
        vp_height = self.viewport().height()
        cur = vsb.value()

        if hint == QAbstractItemView.ScrollHint.EnsureVisible:
            if content_rect.top() < cur:
                vsb.setValue(content_rect.top())
            elif content_rect.bottom() > cur + vp_height:
                vsb.setValue(content_rect.bottom() - vp_height)
        elif hint == QAbstractItemView.ScrollHint.PositionAtTop:
            vsb.setValue(content_rect.top())
        elif hint == QAbstractItemView.ScrollHint.PositionAtBottom:
            vsb.setValue(content_rect.bottom() - vp_height)
        elif hint == QAbstractItemView.ScrollHint.PositionAtCenter:
            vsb.setValue(
                content_rect.top() - (vp_height - content_rect.height()) // 2
            )

    def indexAt(self, point: QPoint) -> QModelIndex:
        content_y = point.y() + self.verticalOffset()
        content_point = QPoint(point.x(), content_y)

        for item in self._all_layout_items():
            if item.rect.contains(content_point) and item.index.isValid():
                return QModelIndex(item.index)  # type: ignore

        return QModelIndex()

    def moveCursor(
        self,
        action: QAbstractItemView.CursorAction,
        modifiers: Qt.KeyboardModifier,
    ) -> QModelIndex:
        current = self.currentIndex()
        items = self._all_layout_items()
        if not items:
            return QModelIndex()

        if not current.isValid():
            first = items[0]
            return (
                QModelIndex(first.index)  # type: ignore
                if first.index.isValid()
                else QModelIndex()
            )

        cur_pmi = QPersistentModelIndex(current)
        cur_pos = -1
        for i, item in enumerate(items):
            if item.index == cur_pmi:
                cur_pos = i
                break

        if cur_pos == -1:
            return current

        if action in (
            QAbstractItemView.CursorAction.MoveRight,
            QAbstractItemView.CursorAction.MoveNext,
        ):
            new_pos = min(cur_pos + 1, len(items) - 1)
        elif action in (
            QAbstractItemView.CursorAction.MoveLeft,
            QAbstractItemView.CursorAction.MovePrevious,
        ):
            new_pos = max(cur_pos - 1, 0)
        elif action == QAbstractItemView.CursorAction.MoveDown:
            cur_rect = items[cur_pos].rect
            cur_center_x = cur_rect.center().x()
            best = cur_pos
            best_dist = float("inf")
            for i in range(cur_pos + 1, len(items)):
                r = items[i].rect
                if r.top() > cur_rect.bottom():
                    dist = abs(r.center().x() - cur_center_x)
                    if dist < best_dist:
                        best_dist = dist
                        best = i
                    elif dist > best_dist:
                        break
            new_pos = best
        elif action == QAbstractItemView.CursorAction.MoveUp:
            cur_rect = items[cur_pos].rect
            cur_center_x = cur_rect.center().x()
            best = cur_pos
            best_dist = float("inf")
            for i in range(cur_pos - 1, -1, -1):
                r = items[i].rect
                if r.bottom() < cur_rect.top():
                    dist = abs(r.center().x() - cur_center_x)
                    if dist < best_dist:
                        best_dist = dist
                        best = i
                    elif dist > best_dist:
                        break
            new_pos = best
        elif action == QAbstractItemView.CursorAction.MoveHome:
            new_pos = 0
        elif action == QAbstractItemView.CursorAction.MoveEnd:
            new_pos = len(items) - 1
        elif action == QAbstractItemView.CursorAction.MovePageUp:
            vp_h = self.viewport().height()
            cur_rect = items[cur_pos].rect
            target_y = cur_rect.top() - vp_h
            new_pos = 0
            for i, item in enumerate(items):
                if item.rect.top() >= target_y:
                    new_pos = i
                    break
        elif action == QAbstractItemView.CursorAction.MovePageDown:
            vp_h = self.viewport().height()
            cur_rect = items[cur_pos].rect
            target_y = cur_rect.top() + vp_h
            new_pos = len(items) - 1
            for i in range(cur_pos, len(items)):
                if items[i].rect.top() >= target_y:
                    new_pos = max(i - 1, cur_pos)
                    break
        else:
            return current

        target_item = items[new_pos]
        if target_item.index.isValid():
            return QModelIndex(target_item.index)  # type: ignore
        return current

    def isIndexHidden(
        self, index: QModelIndex | QPersistentModelIndex
    ) -> bool:
        if not self._is_tree_mode:
            return False
        parent = index.parent()
        if not parent.isValid():
            return False
        node = None
        model = self.model()
        if isinstance(model, QSortFilterProxyModel):
            src = model.mapToSource(parent)
            node = src.internalPointer()
        else:
            node = parent.internalPointer()
        if node is None:
            return False
        node_id = node.node_id
        return node_id in self._collapsed_groups

    def setSelection(
        self, rect: QRect, flags: QItemSelectionModel.SelectionFlag
    ) -> None:
        offset = self.verticalOffset()
        content_rect = rect.translated(0, offset)
        sel = QItemSelection()
        model = self.model()
        if model is None:
            return
        for item in self._all_layout_items():
            if item.rect.intersects(content_rect) and item.index.isValid():
                idx = QModelIndex(item.index)  # type: ignore
                sel.select(idx, idx)
        self.selectionModel().select(sel, flags)

    def visualRegionForSelection(self, selection: QItemSelection) -> QRegion:
        region = QRegion()
        for idx in selection.indexes():
            r = self.visualRect(idx)
            if not r.isNull():
                region += QRegion(r)
        return region

    def updateGeometries(self) -> None:
        vsb = self.verticalScrollBar()
        vp_height = self.viewport().height()
        content_h = self._total_content_height
        if content_h > vp_height:
            vsb.setRange(0, content_h - vp_height)
            vsb.setPageStep(vp_height)
            vsb.setSingleStep(self.scroll_step)
        else:
            vsb.setRange(0, 0)
        super().updateGeometries()

    def resizeEvent(self, event: Any) -> None:
        super().resizeEvent(event)
        self._calculate_layout()
        self._reposition_visible_editors()
        self._schedule_editor_sync()

    def paintEvent(self, event: QPaintEvent) -> None:
        painter = QPainter(self.viewport())
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, False)

        style = get_ayon_style()
        tbl_style = style.model.get_style("AYTableView", self._variant_str)
        tbl_style.set_context(self)
        bg = QColor(tbl_style.get("background-color", "#252a31"))
        painter.fillRect(self.viewport().rect(), bg)

        if self._is_tree_mode:
            self._paint_group_headers(painter, tbl_style)

        painter.end()

    def _paint_group_headers(
        self, painter: QPainter, tbl_style: dict[str, Any]
    ) -> None:
        offset = self.verticalOffset()
        vp_rect = self.viewport().rect()
        header_bg = QColor("transparent")
        header_fg = QColor(tbl_style.get("header-color", "#c1c7ce"))

        expand_icon_size = 16
        expand_icon_padding = 16
        icon_text_padding = 8

        # Set header font based on view font, but larger and bold.
        font = painter.font()
        header_font = QFont(font)
        header_font.setPointSizeF(font.pointSizeF() + 3)
        header_font.setBold(True)
        painter.setFont(header_font)

        for group in self._tree_layout:
            visible_rect = group.header_rect.translated(0, -offset)
            if visible_rect.bottom() < 0:
                continue
            if visible_rect.top() > vp_rect.bottom():
                break

            painter.fillRect(visible_rect, header_bg)

            # Draw expand/collapse icon
            icon_name = (
                "expand_more" if not group.collapsed else "chevron_right"
            )
            try:
                expand_icon = get_icon(icon_name, color=header_fg.name())
                pixmap = expand_icon.pixmap(expand_icon_size, expand_icon_size)
                icon_x = expand_icon_padding
                icon_y = (
                    visible_rect.top()
                    + (visible_rect.height() - expand_icon_size) // 2
                )
                painter.drawPixmap(icon_x, icon_y, pixmap)
            except Exception:
                pass

            # Resolve label color — ForegroundRole returns QBrush, not QColor
            raw_color = group.label_color
            if isinstance(raw_color, QBrush):
                label_color: QColor | None = raw_color.color()
            elif isinstance(raw_color, QColor):
                label_color = raw_color
            else:
                label_color = None

            # Draw label icon if present
            text_x = expand_icon_padding + expand_icon_size + icon_text_padding
            label_icon_size = 16
            if isinstance(group.label_icon, QIcon):
                try:
                    licon_pixmap = group.label_icon.pixmap(
                        label_icon_size, label_icon_size
                    )
                    if not licon_pixmap.isNull():
                        licon_x = text_x
                        licon_y = (
                            visible_rect.top()
                            + (visible_rect.height() - label_icon_size) // 2
                        )
                        painter.drawPixmap(licon_x, licon_y, licon_pixmap)
                        text_x += label_icon_size + icon_text_padding
                except Exception as err:
                    log.debug(
                        "Failed to draw label icon: %s", err, exc_info=True
                    )

            # Draw group label
            text_rect = QRect(
                text_x,
                visible_rect.top(),
                visible_rect.width() - text_x - expand_icon_padding,
                visible_rect.height(),
            )
            painter.setPen(label_color or header_fg)

            label = group.label
            count_str = f"  ({group.child_count})"
            painter.drawText(
                text_rect,
                Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft,
                label + count_str,
            )
        painter.setFont(font)

    def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
        pos = event.pos()

        if self._is_tree_mode and event.button() == Qt.MouseButton.LeftButton:
            offset = self.verticalOffset()
            content_y = pos.y() + offset
            for group in self._tree_layout:
                if group.header_rect.contains(QPoint(pos.x(), content_y)):
                    self._toggle_group(group.node_id)
                    return

        idx = self.indexAt(pos)
        if idx.isValid():
            flags = QItemSelectionModel.SelectionFlag.ClearAndSelect
            modifiers = event.modifiers()
            if modifiers & Qt.KeyboardModifier.ControlModifier:
                flags = QItemSelectionModel.SelectionFlag.Toggle
            elif modifiers & Qt.KeyboardModifier.ShiftModifier:
                flags = QItemSelectionModel.SelectionFlag.Select
            self.selectionModel().select(QItemSelection(idx, idx), flags)
            self.setCurrentIndex(idx)

        super().mousePressEvent(event)

    def mouseDoubleClickEvent(self, event: QtGui.QMouseEvent) -> None:
        idx = self.indexAt(event.pos())
        if idx.isValid():
            self.card_activated.emit(idx)
        super().mouseDoubleClickEvent(event)

    def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
        idx = self.indexAt(event.pos())
        new_pmi = QPersistentModelIndex(idx) if idx.isValid() else None

        if new_pmi != self._hovered_pmi:
            if self._hovered_pmi is not None and self._hovered_pmi.isValid():
                editor = self.indexWidget(QModelIndex(self._hovered_pmi))  # type: ignore
                if isinstance(editor, AYEntityCard):
                    editor.is_hover = False

            self._hovered_pmi = new_pmi

            if new_pmi is not None and new_pmi.isValid():
                editor = self.indexWidget(QModelIndex(new_pmi))  # type: ignore
                if isinstance(editor, AYEntityCard):
                    editor.is_hover = True

        super().mouseMoveEvent(event)

    def leaveEvent(self, event: QtCore.QEvent) -> None:
        if self._hovered_pmi is not None and self._hovered_pmi.isValid():
            editor = self.indexWidget(QModelIndex(self._hovered_pmi))  # type: ignore
            if isinstance(editor, AYEntityCard):
                editor.is_hover = False
        self._hovered_pmi = None
        super().leaveEvent(event)

    def selectionChanged(
        self,
        selected: QItemSelection,
        deselected: QItemSelection,
    ) -> None:
        super().selectionChanged(selected, deselected)

        for idx in deselected.indexes():
            pmi = QPersistentModelIndex(idx)
            if pmi in self._active_editor_pmis:
                editor = self.indexWidget(QModelIndex(pmi))  # type: ignore
                if isinstance(editor, AYEntityCard):
                    editor.is_active = False

        for idx in selected.indexes():
            pmi = QPersistentModelIndex(idx)
            if pmi in self._active_editor_pmis:
                editor = self.indexWidget(QModelIndex(pmi))  # type: ignore
                if isinstance(editor, AYEntityCard):
                    editor.is_active = True

        self.selection_changed.emit(selected, deselected)

    def _toggle_group(self, node_id: str) -> None:
        if node_id in self._collapsed_groups:
            self._collapsed_groups.discard(node_id)
        else:
            self._collapsed_groups.add(node_id)

        self._active_editor_pmis.clear()
        self._calculate_layout()
        self._reposition_visible_editors()
        self.viewport().update()
        self._schedule_editor_sync()

    def _reposition_visible_editors(self) -> None:
        offset = self.verticalOffset()
        vp_rect = self.viewport().rect()

        for item in self._all_layout_items():
            if not item.index.isValid():
                continue
            visible_rect = item.rect.translated(0, -offset)
            if (
                visible_rect.bottom() < 0
                or visible_rect.top() > vp_rect.bottom()
            ):
                continue
            editor = self.indexWidget(QModelIndex(item.index))  # type: ignore
            if editor is not None:
                editor.setGeometry(visible_rect)

    def _get_visible_indexes(self) -> list[QModelIndex]:
        offset = self.verticalOffset()
        vp_rect = self.viewport().rect()
        results = []
        for item in self._all_layout_items():
            if not item.index.isValid():
                continue
            visible_rect = item.rect.translated(0, -offset)
            if visible_rect.bottom() < 0:
                continue
            if visible_rect.top() > vp_rect.bottom():
                continue
            results.append(QModelIndex(item.index))  # type: ignore
        return results

    def get_visible_indexes(self) -> list[QModelIndex]:
        """Return model indices for cards currently visible in the viewport.

        Returns:
            List of valid ``QModelIndex`` objects whose card rects
            intersect the viewport.
        """
        self._calculate_layout()
        return self._get_visible_indexes()

    def refresh_visible_editors(self) -> None:
        """Force ``setEditorData`` to be called for all visible card editors.

        Removes the visible cards from the active-editor set so that the
        next editor-sync pass re-opens their persistent editors and
        updates their data.  This is useful when external state (e.g. a
        thumbnail cache) has changed and the cards need to re-read it.
        """
        for idx in self._get_visible_indexes():
            self._active_editor_pmis.discard(QPersistentModelIndex(idx))
        self._schedule_editor_sync()

    def _maybe_fetch_more(self) -> None:
        """Trigger model pagination when the viewport nears content bottom.

        Must be called **after** ``_calculate_layout()`` has already run so
        that ``_total_content_height`` is up-to-date.  Uses the display model
        (``self.model()``) for all ``canFetchMore`` / ``fetchMore`` calls so
        that proxy mapping is preserved.
        """
        model = self.model()
        if model is None:
            return

        vp_height = self.viewport().height()
        offset = self.verticalOffset()
        total_h = self._total_content_height

        # Deduplicate parents so we never call fetchMore twice per pass.
        fetched: set[QPersistentModelIndex] = set()

        # --- flat-mode root fetch (also runs in tree mode for new top-level
        #     groups) ---
        root = QModelIndex()
        near_bottom = (
            total_h <= vp_height  # content shorter than viewport
            or offset + 2 * vp_height >= total_h
        )
        root_pmi = QPersistentModelIndex(root)
        if near_bottom and root_pmi not in fetched:
            if model.canFetchMore(root):
                model.fetchMore(root)
            fetched.add(root_pmi)

        # --- tree-mode: per-group child fetch ---
        if not self._is_tree_mode:
            return

        for group in self._tree_layout:
            if group.collapsed:
                continue
            if not group.parent_index.isValid():
                continue

            # Only fetch for groups whose content area is within the
            # look-ahead window (2 × viewport height ahead of current pos).
            group_top = group.header_rect.top()
            if group_top - offset >= 2 * vp_height:
                # Group is far below the fold — skip for now.
                break

            pmi = group.parent_index
            if pmi in fetched:
                continue
            group_idx = QModelIndex(pmi)  # type: ignore
            if model.canFetchMore(group_idx):
                model.fetchMore(group_idx)
            fetched.add(pmi)

    def _sync_viewport_editors(self) -> None:
        self._calculate_layout()
        offset = self.verticalOffset()
        vp_rect = self.viewport().rect()

        for item in self._all_layout_items():
            if not item.index.isValid():
                continue
            visible_rect = item.rect.translated(0, -offset)
            if visible_rect.bottom() < 0:
                continue
            if visible_rect.top() > vp_rect.bottom():
                continue

            pmi = item.index
            if pmi not in self._active_editor_pmis:
                self.openPersistentEditor(QModelIndex(pmi))  # type: ignore
                self._active_editor_pmis.add(pmi)

            editor = self.indexWidget(QModelIndex(pmi))  # type: ignore
            if editor is not None:
                editor.setGeometry(visible_rect)

        sel_model = self.selectionModel()
        if sel_model is not None:
            for pmi in self._active_editor_pmis:
                if not pmi.isValid():
                    continue
                idx = QModelIndex(pmi)  # type: ignore
                editor = self.indexWidget(idx)
                if isinstance(editor, AYEntityCard):
                    editor.is_active = sel_model.isSelected(idx)

        self._maybe_fetch_more()

    @property
    def card_width(self) -> int:
        return self._card_width

    @card_width.setter
    def card_width(self, value: int) -> None:
        self._card_width = value
        self._delegate._card_width = value
        self._active_editor_pmis.clear()
        self._schedule_layout_update()

    @property
    def card_spacing(self) -> int:
        return self._card_spacing

    @card_spacing.setter
    def card_spacing(self, value: int) -> None:
        self._card_spacing = value
        self._schedule_layout_update()

    @property
    def card_data_mapper(
        self,
    ) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
        return self._card_data_mapper

    @card_data_mapper.setter
    def card_data_mapper(
        self, value: Callable[[dict[str, Any]], dict[str, Any]] | None
    ) -> None:
        self._card_data_mapper = value
        self._delegate._card_data_mapper = value or (lambda r: {})
        self._active_editor_pmis.clear()
        self._schedule_layout_update()

get_visible_indexes()

Return model indices for cards currently visible in the viewport.

Returns:

Type Description
list[QModelIndex]

List of valid QModelIndex objects whose card rects

list[QModelIndex]

intersect the viewport.

Source code in client/ayon_ui_qt/components/card_view.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
def get_visible_indexes(self) -> list[QModelIndex]:
    """Return model indices for cards currently visible in the viewport.

    Returns:
        List of valid ``QModelIndex`` objects whose card rects
        intersect the viewport.
    """
    self._calculate_layout()
    return self._get_visible_indexes()

refresh_visible_editors()

Force setEditorData to be called for all visible card editors.

Removes the visible cards from the active-editor set so that the next editor-sync pass re-opens their persistent editors and updates their data. This is useful when external state (e.g. a thumbnail cache) has changed and the cards need to re-read it.

Source code in client/ayon_ui_qt/components/card_view.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
def refresh_visible_editors(self) -> None:
    """Force ``setEditorData`` to be called for all visible card editors.

    Removes the visible cards from the active-editor set so that the
    next editor-sync pass re-opens their persistent editors and
    updates their data.  This is useful when external state (e.g. a
    thumbnail cache) has changed and the cards need to re-read it.
    """
    for idx in self._get_visible_indexes():
        self._active_editor_pmis.discard(QPersistentModelIndex(idx))
    self._schedule_editor_sync()