2016-05-10 58 views
0

我有qListView填充項目實際上是我從文件夾中讀取的文件名。 現在,使用上下文菜單動作「刪除」,我在後臺刪除相應的文件。在qListView中,刪除的項目沒有在視圖中得到更新

問題是qListView,沒有得到更新即。它仍然顯示我已經刪除的項目。

我的查詢是,如何動態刷新視圖?我是新來的MVC編程,想知道是否有可能在模型中做到這一點?或者,我必須使用遞歸函數來更新視圖。順便說一句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 

感謝您的時間:)

+0

你的模型是什麼?爲什麼你不是從模型中刪除項目呢?模型應該處理刪除文件。 –

+0

嗨庫巴,我更新模型code.Model刪除文件和更新視圖,我需要檢查。 –

+1

你正在嘗試做一些已經完成的事情。請參閱[QDirModel](http://doc.qt.io/qt-5/qdirmodel.html)。 –

回答

1

QStandardItemModel

奇拉格如果你正在寫你自己的模型,它會消耗大量的時間。相反,請查看QStandardItemModel,因爲它爲我們提供了許多已經實施的內容,並且需要根據我們的要求在代碼中使用它們。

我正在使用此QStandardItemModel並有我自己的上下文菜單。

self.model = QtGui.QStandardItemModel() 

如果讓我選擇刪除我的代碼選項,這段代碼將幫助我們在刪除列表視圖我們選擇的項目(即刪除特定行)。

item_to_be_deleted = self.listView.selectionModel().currentIndex().data().toString() 
      model = self.model 
      for item in model.findItems(item_to_be_deleted): 
       model.removeRow(item.row()) 
+0

感謝Juna的回答。但是我使用的QFileSystemModel與Marek R建議的QDirModel類似(性能明智地推進到)。它很容易管理和工作像魅力! –

+0

@chirag是這段代碼對於動態更新你的listview有幫助..? –

相關問題