【发布时间】:2025-12-19 07:30:10
【问题描述】:
我在 qListView 中填充了项目,这些项目实际上是我从文件夹中读取的文件名。 现在,使用上下文菜单操作“删除”,我正在后台删除相应的文件。
问题是 qListView,没有得到更新,即。它仍然显示我已经删除的项目。
我的问题是,如何动态刷新视图?我是 MVC 编程的新手,想知道是否可以在模型中实现它?或者,我是否必须使用递归函数来更新视图。 BTW m 使用 qAbstract 列表模型,甚至尝试了 currentItemChanged 和 dataChanged 但似乎没有任何效果。
TestStepInstViewHdlr 是 QListView 类的实例:
TestStepInstViewHdlr.setSelectionMode(QAbstractItemView.MultiSelection)
TestStepInstViewHdlr.show()
TestStepViewHdlr.stepSelected.connect(getTestStepName)
TestStepInstViewHdlr.itemSelectionChanged.connect(TestStepInstViewHdlr.getInstanceName)
TestStepInstViewHdlr.customContextMenuRequested.connect(TestStepInstViewHdlr.onContext)
def getInstanceName(self):
index = self.selectedIndexes()
val = ""
valArray = []
for i in index:
val = i.data()
valArray.append(val)
print(valArray)
return valArray
def onContext(self, position):
instArray = []
constHdlr = const.Constant()
# Create a menu
menu = QtGui.QMenu()
rmvAction = menu.addAction("Remove")
canAction = menu.addAction("Cancel")
action = menu.exec_(self.mapToGlobal(position))
if action == rmvAction:
instArray = self.getInstanceName()
path = constHdlr.TEST_STEP_INSTANCE_PATH + StepName+"\\"
for inst in instArray:
path = path + inst
if os.path.isfile(path):
os.remove(path)
if action == canAction:
pass
我的模型是:
class TestStepInstListModel(QtCore.QAbstractListModel):
def __init__(self, TestSteps = [], parent = None):
QtCore.QAbstractListModel.__init__(self, parent)
self.__TestSteps = TestSteps
def rowCount(self, parent = None):
return len(self.__TestSteps)
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
row = index.row()
return self.__TestSteps[row]
def flags(self, index):
return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
def removeRows(self, position, rows, parent = QtCore.QModelIndex()):
self.beginRemoveRows(parent, position, position + rows - 1)
for i in range(rows):
value = self.__TestSteps[position]
self.__TestSteps.remove(value)
self.endRemoveRows()
return True
感谢您的宝贵时间 :)
【问题讨论】:
-
你的型号是什么?你为什么不从模型中删除项目呢?然后模型应该处理删除文件。
-
嗨,Kuba,我更新了模型代码。模型要删除文件并更新视图,我需要检查一下。
-
您正在尝试做一些已经完成的事情。见QDirModel。
-
您在哪里拨打
removeRows?真的执行了吗?
标签: python qt model-view-controller pyqt pyqt4