使用QTableView
and QAbstractTableModel
,我希望能够在表格中选择多个单元格并进行编辑影响所有选定的单元格。这就是我目前的做法,其中包括将view
( QTableView
) 和proxy_model
( QSortFilterProxyModel
) 传递到类中,以便我可以访问它们(以获取适当的行和列):
import sys
from pprint import pprint
try:
from PySide2 import QtWidgets, QtCore
except ImportError:
from PyQt5 import QtWidgets, QtCore
class MyTableModel(QtCore.QAbstractTableModel):
def __init__(self,
view,
proxy_model,
table_data,
parent=None):
QtCore.QAbstractTableModel.__init__(self, parent)
self.table_data = table_data
self.view = view
self.proxy_model = proxy_model
def rowCount(self, parent):
return len(self.table_data)
def columnCount(self, parent):
return len(self.table_data[0])
def flags(self, index):
# Original, inherited flags:
original_flags = super(MyTableModel, self).flags(index)
return original_flags | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
column = index.column()
item = index.internalPointer()
if item is not None:
print(item)
value = self.table_data[row][column]
return value
return None
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
selection_model = self.view.selectionModel()
selected_indexes = selection_model.selectedIndexes()
for selected_index in selected_indexes:
mapped_index = self.proxy_model.mapToSource(selected_index)
selected_row = mapped_index.row()
selected_column = mapped_index.column()
self.table_data[selected_row][selected_column] = value
pprint(self.table_data)
self.dataChanged.emit(index, selected_index) # from, to
return True
return False
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
table_data = [['one', 'two', 'three'], ['four', 'five', 'six']]
view = QtWidgets.QTableView()
proxy_model = QtCore.QSortFilterProxyModel()
model = MyTableModel(view=view, proxy_model=proxy_model, table_data=table_data)
proxy_model.setSourceModel(model)
proxy_model.setDynamicSortFilter(True)
view.setModel(proxy_model)
view.setSortingEnabled(True) # requires proxy model
view.sortByColumn(0, QtCore.Qt.AscendingOrder)
view.horizontalHeader().setStretchLastSection(True)
view.horizontalHeader().setSectionsMovable(True)
view.show()
app.exec_()
我怀疑我不必通过view
并proxy_model
进入班级,并且可以通过其他方式访问这些对象。这是可能的,如果是这样 - 怎么做?
我知道我的示例是特定于 Python 的,但我的问题实际上是一个与绑定无关的问题,所以我也用qt
.