[Python] How to make QTableView's drag selection behave like a QTreeView

Discussão em 'Python' iniciado por Stack, Setembro 12, 2025.

  1. Stack

    Stack Membro Participativo

    There's a difference in behaviour between QTableView and QTreeView when it comes to selecting multiple items by dragging the mouse.

    In a QTreeView you can start outside the populated area and drag over the items, and they will be selected. In a QTableView this is not not possible. In order to drag and select items you have to start dragging on an item.

    Is it possible to make a QTableView behave like a QTreeView in this aspect?

    Here's a little example where you can experience the difference:

    from PyQt6.QtCore import QAbstractTableModel, Qt
    from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QTableView, QTreeView


    class TModel(QAbstractTableModel):
    def __init__(self):
    super().__init__()
    self.d = [[1, 2], [3, 4], [5, 6]]

    def columnCount(self, parent=None):
    return 2

    def rowCount(self, parent=None):
    return len(self.d)

    def data(self, index, role=1):
    if role == Qt.ItemDataRole.DisplayRole:
    return self.d[index.row()][index.column()]
    return None


    class Window(QWidget):
    def __init__(self):
    super().__init__()
    view1 = QTreeView()
    view2 = QTableView()
    for v in (view1, view2):
    v.setSelectionMode(v.SelectionMode.ExtendedSelection)
    model = TModel()
    view1.setModel(model)
    view2.setModel(model)

    lay = QVBoxLayout(self)
    lay.addWidget(view1)
    lay.addWidget(view2)


    app = QApplication([])
    win = Window()
    win.show()
    app.exec()

    Continue reading...

Compartilhe esta Página