如何在Qt代理模型中获取整个选定的行?

时间:2016-02-24 05:16:17

标签: python qt pyqt

下面的代码是一个有效的QTableView,它使用的是QAbstractTableModel,它使用的是QSortFilterProxyModel。我设法弄清楚如何从所选行的 单元中获取数据,而不是一次性获取整行(例如,作为列表字符串)。请问我可以提供一些尝试的建议吗?

(我使用的是Python,但如果有人知道如何使用其他语言进行操作,我会尝试进行翻译...)

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys


class CustomTableModel(QAbstractTableModel):
    def __init__(self, cells=[[]], headers=[]):
        super(CustomTableModel, self).__init__()
        self._cells = cells
        self._headers = headers

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

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

    def columnCount(self, parent=None):
        return len(self._headers)

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsSelectable


class CustomSortFilterProxyModel(QSortFilterProxyModel):
    def __init__(self):
        super(CustomSortFilterProxyModel, self).__init__()

    def get_selected_row(self):
        # Unsure what to put here??
        pass


def table_clicked():
    selected_indexes = table_view.selectionModel().selectedRows()
    first_cell_selected = proxy_model.data(proxy_model.index(selected_indexes[0].row(), 0), Qt.DisplayRole).toString()
    print(first_cell_selected)

    # But rather than the above I would like to be able to do something like:
    print(proxy_model.get_selected_row())
    # and for it to print out everything in the row e.g. ['Cell 1', 'Cell 2', 'Cell 3']


app = QApplication(sys.argv)

table_data = [["Cell 1", "Cell 2", "Cell 3"], ["Cell 4", "Cell 5", "Cell 6"]]
table_headers = ["Header 1", "Header 2", "Header 3"]

model = CustomTableModel(table_data, table_headers)

proxy_model = CustomSortFilterProxyModel()
proxy_model.setDynamicSortFilter(True)
proxy_model.setSourceModel(model)

table_view = QTableView()
table_view.setModel(proxy_model)
table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
table_view.setSelectionMode(QAbstractItemView.SingleSelection)
table_view.setSortingEnabled(True)
table_view.clicked.connect(table_clicked)
table_view.show()

sys.exit(app.exec_())

可能与How to get Index Row number from Source Model

有关

1 个答案:

答案 0 :(得分:2)

没有现成的方法来获取整行的数据。 您必须遍历现有列。

基本上,您可以转换现有的行:

first_cell_selected = proxy_model.data(proxy_model.index(selected_indexes[0].row(), 0), Qt.DisplayRole).toString()

进入列表理解以获取每个单元格的内容:

row = selected_indexes[0].row()
row_data = [proxy_model.index(row, col).data().toString()
            for col in xrange(proxy_model.columnCount())]

顺便说一下:QModelIndex还提供了data()方法,Qt.DisplayRole是此处的默认角色。所以你可以简化

proxy_model.data(proxy_model.index(row, col), Qt.DisplayRole)

proxy_model.index(row, col).data()

有点容易阅读。