我有QTreeView
QSortFilterProxyModel
。当我单击视图的任何项目时,将从单击的行打印索引。在设置过滤器之前和之后,它会打印相同的索引。
我需要removeRow()
这个,但是当我输入索引时,它会从列表中删除不正确的项目:/
如何删除正确的选定行?
示例:
未排序
ITEM 1
ITEM 2 -> Click: Print ITEM2 and this is removed
ITEM 3
ITEM 4
排序
ITEM 2
ITEM 4 -> Click: Print ITEM2 and ITEM2 is removed :/
init
self.menuIndex = None
self.mModelMenu = QtGui.QStandardItemModel(0, 4, self)
self.mModelMenu.setHeaderData(0, QtCore.Qt.Horizontal, "Id")
self.mModelMenu.setHeaderData(1, QtCore.Qt.Horizontal, "Descripcion")
self.mModelMenu.setHeaderData(2, QtCore.Qt.Horizontal, "Categoria")
self.mModelMenu.setHeaderData(3, QtCore.Qt.Horizontal, "Cantidad")
self.mProxyModelMenu = QtGui.QSortFilterProxyModel()
self.mProxyModelMenu.setDynamicSortFilter(True)
self.mProxyModelMenu.setSourceModel(self.mModelMenu)
self.mTreeView = QtGui.QTreeView()
self.mTreeView.setRootIsDecorated(False)
self.mTreeView.setAlternatingRowColors(True)
self.mTreeView.setModel(self.mProxyModelMenu)
self.mTreeView.setSortingEnabled(True)
self.mTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.mTreeView.resizeColumnToContents(0)
self.mTreeView.clicked.connect(self.getIndex)
mPushButton1 = QtGui.QPushButton("Borrar")
mPushButton1.clicked.connect(self.newInMenu)
def getIndex()
print(index.row())
self.menuIndex = index.data(index.row())
print(index.data(index.row()))
# print(index.data(QtCore.Qt.DisplayRole))
def removeFromMenu(self):
toRemove = self.menuIndex
self.mModelMenu.removeRow(0) #this delete the last row, but i need delete current selected row
答案 0 :(得分:1)
使用代理模型的最简单方法是避免使用原始模型并尽可能使用QSortFilterProxyModel
方法。
E.g。只需在代理模型上调用removeRow
:
def removeFromMenu(self)
selIndexes = self.mTreeView.selectedIndexes()
if len(selIndexes):
first = selIndexes[0]
self.mProxyModelMenu.removeRow(first.row(), first.parent())
应该这样做。
答案 1 :(得分:0)
使用QSortFilterProxyModel
时,您有两种类型的索引:代理索引(您在视图中看到的顺序)和原始模型的源索引(QStandardItemModel
中的顺序)
该视图将为您提供代理索引,您可以使用mapToSource返回源索引,如下所示:
#get first selected index
proxy_index = self.mTreeView.selectedIndexes()[0]
#convert
source_index=self.mProxyModelMenu.mapToSource(proxy_index)
#delete row in source model
self.mModelMenu.removeRow(source_index.row())