在PyQt5中,我尝试使用QItemDelegate在表格的单元格中显示图标,而不是文本字符串。实际上,我使用以下命令构造QItemDelegate的子类:
de = MyDelegate(self.attribute_table_view)
这里的dself.attribute_table_view
是一个` `QTableView‘对象。
我尝试使用以下命令在特定列的每个单元格中绘制一个图标:
class MyDelegate(QItemDelegate):
def __init__(self, parent=None, *args):
QItemDelegate.__init__(self, parent, *args)
def paint(self, painter, option, index):
painter.save()
value = index.data(Qt.DisplayRole)
line_1x = QPixmap('line_1x.png')
painter.setBrush(Qt.gray)
painter.setPen(Qt.black)
painter.drawPixmap(QRectF(0, 0, 48, 24), line_1x, QRectF(0, 0, 48, 24))
painter.restore()
使用painter.drawPixmap()
,我如何告诉它像使用painter.drawText(option.rect, Qt.AlignVCenter, value)
一样在表格中绘制每个单元格
此外,我还注意到,如果我输入的文件名对于.png文件不存在,则当前脚本不会报告任何错误。如果.png文件不存在,应该由报告错误吗?
我当前的模型是一个QgsAttributeTableModel,我想用图标呈现一列中所有单元格的当前字符串值,其中使用的图标取决于字符串值。
发布于 2018-09-27 23:16:06
在这个答案中,我将展示几种方法,您可以根据问题的复杂程度进行选择。
1.图标数量固定,一列重复使用。
逻辑是加载图标一次,并将其作为属性传递给委托,然后根据您的逻辑获得列表的图标,因为它修改了get_icon()
方法。并且我们通过QIcon的paint()
方法来绘制图标。
class MyDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, icons, parent=None):
super(MyDelegate, self).__init__(parent)
self._icons = icons
def get_icon(self, index):
# get the icon according to the condition:
# In this case, for example,
# the icon will be repeated periodically
icon = self._icons[ index.row() % len(self._icons) ]
return icon
def paint(self, painter, option, index):
icon = self.get_icon(index)
icon.paint(painter, option.rect, QtCore.Qt.AlignCenter)
如何重用列必须使用setItemDelegateForColumn()
方法将委托设置为列
self.attribute_table_view = QtWidgets.QTableView()
self.attribute_table_view.setModel(your_model)
column_icon = 1
icons = [QtGui.QIcon(QtCore.QDir.current().absoluteFilePath(name)) for name in ["clear.png", "heart.png","marker.png", "pen.png"]]
delegate = MyDelegate(icons, self.attribute_table_view)
self.attribute_table_view.setItemDelegateForColumn(column_icon, delegate)
我注意到,如果我为.png文件输入了一个不存在的文件名,当前的脚本不会报告任何错误。如果.png文件不存在,应该由报告错误吗?
如果文件不存在,Qt将不会发出通知,您必须进行验证,例如使用isNull()
函数。有两种通知方式:
第一个是返回一个布尔值,指示是否加载了数据,但当使用构造函数时,它只返回构造的对象并抛出。
特别是Qt通知有错误的另一种方式是通过信号,但这些只适用于QObject和QIcon,QPixmap,QImage不是QObjects。
因此,总之,验证或不验证的责任落在了开发人员身上。
https://stackoverflow.com/questions/52545316
复制相似问题