how to preserve selection when sorting QTableView

MJB

How can I preserve the selection of items when I sort the table? In the below example the selection is always fixed to the row index i.e. if I select first row, then after sorting always first row is selected, not the actual row that I had selected.

import sys

from PySide2 import QtWidgets, QtGui, QtCore
from PySide2.QtCore import Qt


class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole:
            return self._data[index.row()][index.column()]

    def sort(self, column, order):
        if order == Qt.DescendingOrder:
            rev = True
        else:
            rev = False
        self.layoutAboutToBeChanged.emit()
        self._data.sort(key=lambda x: x[column], reverse=rev)
        self.layoutChanged.emit()

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

    def columnCount(self, parent=None):
        return len(self._data[0])


class Main(QtWidgets.QDialog):
    def __init__(self, data):
        super().__init__()
        self.layout = QtWidgets.QVBoxLayout()
        self.table = QtWidgets.QTableView()
        self.table.setSortingEnabled(True)
        self.table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
        self.model = TableModel(data)
        self.table.setModel(self.model)
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)


def main():
    app = QtWidgets.QApplication(sys.argv)
    data = [
        [1,2,3,4],
        [5,6,7,8],
        [6,5,4,3],
        [2,1,0,9]
    ]
    m = Main(data)
    m.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
eyllanesc

When implementing the sort method you are modifying the data and there is no way that the view knows the new position of the items, instead of modifying the data you must modify the indices using a QSortFilterProxyModel:

import sys

from PySide2 import QtCore, QtGui, QtWidgets


class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            return self._data[index.row()][index.column()]

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

    def columnCount(self, parent=None):
        return len(self._data[0])


class Main(QtWidgets.QDialog):
    def __init__(self, data):
        super().__init__()
        self.layout = QtWidgets.QVBoxLayout()
        self.table = QtWidgets.QTableView()
        self.table.setSortingEnabled(True)
        self.table.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows
        )
        self.model = TableModel(data)
        self.proxy = QtCore.QSortFilterProxyModel()
        self.proxy.setSourceModel(self.model)
        self.table.setModel(self.proxy)
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)


def main():
    app = QtWidgets.QApplication(sys.argv)
    data = [[1, 2, 3, 4], [5, 6, 7, 8], [6, 5, 4, 3], [2, 1, 0, 9]]
    m = Main(data)
    m.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to preserve shell script line spacing when reading stdout?

分類Dev

How can I preserve certain files when compiling as a single .exe?

分類Dev

How to preserve spaces in text input field when echoing php variable

分類Dev

how to tell rsync to preserve time stamp on files when source tree has a mounted point

分類Dev

Preserve selection after clicking a custom button in tinyMCE issue

分類Dev

How to create form when second dropdown depends on the first dropdown selection

分類Dev

postgres is ignoring "-" when sorting

分類Dev

Preserve xts index when using rowSums on xts

分類Dev

Preserve the state of fragment when previous button is clicked

分類Dev

preserve format when extracting from list in R

分類Dev

preserve entity references when parsing xml

分類Dev

QTableView doesn't update edited cell when button is clicked

分類Dev

Ignore nil elements when sorting

分類Dev

Pandoc lua filter: How to preserve footnotes' formatting?

分類Dev

How to preserve attachment content between render passes

分類Dev

How to preserve initial state in React Component?

分類Dev

Alert Dialog not Change when selection

分類Dev

how to parametrize python sorting

分類Dev

How to ignore None values with operator.itemgetter when sorting a list of dicts?

分類Dev

How to connect spinner item selection for next selection?

分類Dev

How do I populate a QTableView with asynchronous fetched data?

分類Dev

How to make QTableView refresh Background color after it loads data again

分類Dev

Preserve environment variables when spawning shiny processes within a container

分類Dev

Django alterField does not preserve NOT NULL when modifying max_length

分類Dev

How to apply nested sorting in javascript

分類Dev

How to customize sorting behaviour in QTableWidget

分類Dev

How to combine sorting parameters in lists?

分類Dev

How to understand array sorting in Swift

分類Dev

angular-datatables not sorting when formatting date

Related 関連記事

  1. 1

    How to preserve shell script line spacing when reading stdout?

  2. 2

    How can I preserve certain files when compiling as a single .exe?

  3. 3

    How to preserve spaces in text input field when echoing php variable

  4. 4

    how to tell rsync to preserve time stamp on files when source tree has a mounted point

  5. 5

    Preserve selection after clicking a custom button in tinyMCE issue

  6. 6

    How to create form when second dropdown depends on the first dropdown selection

  7. 7

    postgres is ignoring "-" when sorting

  8. 8

    Preserve xts index when using rowSums on xts

  9. 9

    Preserve the state of fragment when previous button is clicked

  10. 10

    preserve format when extracting from list in R

  11. 11

    preserve entity references when parsing xml

  12. 12

    QTableView doesn't update edited cell when button is clicked

  13. 13

    Ignore nil elements when sorting

  14. 14

    Pandoc lua filter: How to preserve footnotes' formatting?

  15. 15

    How to preserve attachment content between render passes

  16. 16

    How to preserve initial state in React Component?

  17. 17

    Alert Dialog not Change when selection

  18. 18

    how to parametrize python sorting

  19. 19

    How to ignore None values with operator.itemgetter when sorting a list of dicts?

  20. 20

    How to connect spinner item selection for next selection?

  21. 21

    How do I populate a QTableView with asynchronous fetched data?

  22. 22

    How to make QTableView refresh Background color after it loads data again

  23. 23

    Preserve environment variables when spawning shiny processes within a container

  24. 24

    Django alterField does not preserve NOT NULL when modifying max_length

  25. 25

    How to apply nested sorting in javascript

  26. 26

    How to customize sorting behaviour in QTableWidget

  27. 27

    How to combine sorting parameters in lists?

  28. 28

    How to understand array sorting in Swift

  29. 29

    angular-datatables not sorting when formatting date

ホットタグ

アーカイブ