gpt4 book ai didi

python - 向 QTreeView/QFileSystemModel 中的项目添加附加信息

转载 作者:太空宇宙 更新时间:2023-11-03 14:37:22 24 4
gpt4 key购买 nike

我想根据数据库中存储的多个属性以及项目是文件夹还是文件来不同地渲染 QTreeView 中的每个项目。但是,我不明白 QTreeView 或 QFileSystemModel 如何与委托(delegate)进行通信。每当必须绘制一个项目时,包括在初始化期间,我希望为委托(delegate)提供它所需的所有参数,然后在委托(delegate)中使用一系列 if 语句来设置特定项目的绘制方式画。我只找到了 .setItemDelegate 方法,不知道何时或如何实际调用委托(delegate),也不知道它如何循环访问模型中的所有项目。以下是基于在线 Material 的示例。有两个问题:

  1. 我在注释中放置了无法运行的代码。一旦我了解了委托(delegate)如何从 QTreeView(或调用类)接收信息,我相信我可以完成剩下的工作。

  2. 我无法让 QTreeView 的子类显示文件夹和文件图标。

代码:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class fileSystemDelegate(QItemDelegate):
def __init__(self, parent=None):
QItemDelegate.__init__(self, parent) #shouldn't this insure the icons are drawn?

def paint(self, painter, option, index):
painter.save()

# set background
painter.setPen(QPen(Qt.NoPen))
if option.state & QStyle.State_Selected: #DURING DRAW LOOP: idx = self.currentIndex(); if self.fileSystemModel.isDir(idx): PAINT RED
painter.setBrush(QBrush(Qt.red))
else:
painter.setBrush(QBrush(Qt.white)) #ELSE PAINT WHITE
painter.drawRect(option.rect)

# draw item
painter.setPen(QPen(Qt.black))
text = index.data(Qt.DisplayRole)
painter.drawText(option.rect, Qt.AlignLeft, text) #there is no painter.drawIcon?

painter.restore()

class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)

delegate = fileSystemDelegate()
self.setItemDelegate(delegate) # how to provide delegate with additional info about the item to be drawn ?

self.fileSystemModel = QFileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)

if __name__ == '__main__':

app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())

编辑1:

我以字典的形式添加了一个示例“数据库”,并将方法更改为依赖数据方法而不是委托(delegate)。我希望每当信息显示在树中时此代码都会执行字典查找,因此当用户在 Microsoft Windows 计算机上输入 C:\Program Files\Internet Explorer\ 时,该代码会打印到终端。但是,它只显示目录,而不将任何内容打印到终端。我想知道:

  1. 如何在数据方法中获取 if 语句,以便在绘制显示中的每个项目时触发它们?

  2. 如何在同一行上显示默认图标后显示图标?

代码:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

database = {'C:\Program Files\Internet Explorer\ExtExport.exe':(1,3), 'C:\Program Files\Internet Explorer\iexplore.exe':(0,0)}

class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)

self.fileSystemModel = QFileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)

def data(self, index, role=Qt.DisplayRole):
if index.isValid():
path = self.fileSystemModel.filePath(index)
if self.fileSystemModel.isDir(index):
if database.get(path) != None:
if database[path][0] > 0:
print("Acting on custom data 0.") # add another icon after the regular folder icon

if database[path][1] > 0:
print("Acting on custom data 1.") # add another (different) icon after the regular folder or previous icon

if __name__ == '__main__':

app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())

编辑 2:

对模型进行子类化确实会产生影响。现在,脚本似乎正在对每个项目调用我的新数据方法。不幸的是,数据方法还不起作用,因此结果是没有图标或文本的 TreeView 。有时我会收到错误:“QFileSystemWatcher:无法添加路径:C:/PerfLogs”。根据网上的例子,我已经评论了我认为我的错误可能存在的地方,但我还无法让它发挥作用。我做错了什么?

import sys
from PySide.QtCore import *
from PySide.QtGui import *

database = {'C:\Program Files\Internet Explorer\ExtExport.exe':(1,3), 'C:\Program Files\Internet Explorer\iexplore.exe':(0,0)}

class newFileModel(QFileSystemModel):

def __init__(self, parent=None):
QFileSystemModel.__init__(self, parent)
#self.elements = [[Do I need this? What should go here?]]

def data(self, index, role=Qt.DisplayRole):
if index.isValid():
path = self.filePath(index)
if self.isDir(index):
if database.get(path) != None:
if database[path][0] > 0:
print("Acting on custom data 0.") # I can add code here for different color text, etc.

if database[path][1] > 0:
print("Acting on custom data 1.") # I'll add code later
#return self.data(index, role) # Do I need this about here?


class fileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)

self.fileSystemModel = newFileModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)


if __name__ == '__main__':

app = QApplication(sys.argv)
window = fileSystemBrowser()
window.show()
sys.exit(app.exec_())

最佳答案

这是一个基本演示,展示了如何添加带有图标和其他格式的额外列。请注意,我们尝试标准化文件路径,以便比较和字典查找更加可靠:

import sys
from PySide.QtCore import *
from PySide.QtGui import *

database = {
QFileInfo('C:\Program Files\Internet Explorer\ExtExport.exe').absoluteFilePath(): (1, 3),
QFileInfo('C:\Program Files\Internet Explorer\iexplore.exe').absoluteFilePath(): (0, 0),
}

class FileSystemModel(QFileSystemModel):
def __init__(self, parent=None):
super().__init__(parent)
style = qApp.style()
self.icons = [
style.standardIcon(QStyle.SP_MessageBoxInformation),
style.standardIcon(QStyle.SP_MessageBoxWarning),
]

def columnCount(self, parent=QModelIndex()):
return super().columnCount(parent) + 1

def data(self, index, role=Qt.DisplayRole):
extra = False
if index.isValid():
extra = index.column() == self.columnCount(index.parent()) - 1
info = self.fileInfo(index)
path = info.absoluteFilePath()
if path in database:
major, minor = database[path]
print('found:', (major, minor), path)
if extra:
if role == Qt.DecorationRole:
if major > 0:
return self.icons[0]
else:
return self.icons[1]
elif role == Qt.DisplayRole:
return '%s/%s' % (major, minor)
elif role == Qt.ForegroundRole:
if minor > 2:
return QColor('red')
if not extra:
return super().data(index, role)

def headerData(self, section, orientation, role=Qt.DisplayRole):
if (orientation == Qt.Horizontal and
role == Qt.DisplayRole and
section == self.columnCount() - 1):
return 'Extra'
return super().headerData(section, orientation, role)

class FileSystemBrowser(QTreeView):
def __init__(self, parent=None):
super().__init__(parent)
self.fileSystemModel = FileSystemModel()
self.fileSystemModel.setRootPath(QDir.currentPath())
self.setModel(self.fileSystemModel)
self.header().moveSection(self.fileSystemModel.columnCount() - 1, 1)

if __name__ == '__main__':

app = QApplication(sys.argv)
window = FileSystemBrowser()
window.show()
sys.exit(app.exec_())

编辑:

data 方法中使用的角色均记录在 ItemDataRole enum 下,介绍如下:

Each item in the model has a set of data elements associated with it, each with its own role. The roles are used by the view to indicate to the model which type of data it needs. Custom models should return data in these types.

对于已添加的额外列,需要提供所有内容,因为它是虚拟列,不属于底层模型的一部分。但对于其他列,我们可以调用基类实现来获取默认值(当然,如果需要,我们也可以为这些列返回自定义值来修改现有行为)。

关于python - 向 QTreeView/QFileSystemModel 中的项目添加附加信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46835109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com