0
我構建了一個可檢查的樹視圖,列出了文件/文件夾。我正在保存被檢查的文件/文件夾,並將它們寫入文件。當我再次啓動樹視圖時,我希望檢查所有保存的路徑。但是我無法獲得路徑的正確索引。在樹形視圖中獲取可用路徑的索引
class CheckableModel(QtGui.QFileSystemModel):
def __init__(self, tView, parent=None):
QtGui.QFileSystemModel.__init__(self, tView)
self.tView = tView
self.checks = {}
backupstr = fileread(os.path.join(os.path.expanduser("~"), "Desktop"), "saved.txt", "utf-16")
if backupstr:
backuplist = backupstr.split('\n')
for backupitem in backuplist:
self.setData(self.index(backupitem), QtCore.Qt(QtCore.Qt.Checked), QtCore.Qt.CheckStateRole)
我試着用self.index(QString)
,但它不能正常工作的所有時間。就像,當我試圖從self.checks
中刪除這個條目時(取消選中以這種方式加載的節點),它無法在self.checks
中找到該索引。
那麼,當我們只有路徑時,在樹視圖中獲取索引(QModelIndex
)的正確方法是什麼?
編輯:
setData()
被實施如下:
def setData(self, index, value, role):
if (role == QtCore.Qt.CheckStateRole) and (index.column() == 0):
if value == QtCore.Qt.Checked:
self.removesubfolders(index)
self.checks[index] = value
count = self.rowCount(index)
self.dataChanged.emit(index.child(0, 0), index.child(count - 1, 0))
self.tView.collapse(index)
return True
elif value == QtCore.Qt.Unchecked:
self.removesubfolders(index)
self.tView.collapse(index)
return True
return QtGui.QFileSystemModel.setData(self, index, value, role)
def removesubfolders(self, index):
checkedItems = []
for otherindex, othervalue in self.checks.items():
if othervalue.toBool():
checkedItems.append(str(self.filePath(otherindex)))
uncheckpath = str(self.filePath(index))
indices = [removeindex for removeindex in checkedItems if (removeindex.find(uncheckpath) != -1)]
for idx in indices:
localidx = self.index(idx)
if localidx in self.checks:
self.checks.pop(localidx)
您能提供一個更完整的例子嗎?例如,如何添加/刪除'self.checks'中的條目,因爲它似乎是一個問題? – Mel
對不起,我忙於我的項目。我找到了一個工作。我現在保持文件/文件夾路徑的字典來跟蹤選中的項目(如答案中發佈的那樣)。它似乎工作。如果您可以建議更正或提供替代解決方案,將非常感激。 – Harsh