我正在使用QComboBox显示来自数据库的一些MAC地址作为整数。为了以更熟悉的“点缀八位字节”格式显示它们,我创建了以下 QStyledItemDelegate :
class MacAddressDelegate(QStyledItemDelegate):
def __init__(self):
super(MacAddressDelegate, self).__init__()
def _intMacToString(self, intMac):
hexmac = ('%x' % intMac).zfill(12)
return ':'.join(s.encode('hex') for s in hexmac.decode('hex')).upper()
def setModelData(self, editor, model, index):
macstr = editor.text().__str__()
intmac = int(macstr.replace(':',''), 16)
model.setData(index, intmac, Qt.EditRole)
def setEditorData(self, editor, index):
intmac = index.model().data(index, Qt.EditRole)
if intmac.isValid():
editor.setText(self._intMacToString(intmac.toULongLong()[0]))
def paint(self, painter, option, index):
# let the base class initStyleOption fill option with the default values
super(MacAddressDelegate, self).initStyleOption(option, index)
if option.state & QStyle.State_Selected:
painter.fillRect(option.rect, option.palette.highlight())
painter.setPen(Qt.color0)
else:
painter.setPen(Qt.color1)
intmac = index.model().data(index, Qt.DisplayRole)
if intmac.isValid():
text = self._intMacToString(intmac.toULongLong()[0])
painter.drawText(option.rect, Qt.AlignVCenter, text)
但是当我从 QSqlTableModel 设置模型并将 QComboBox 委托给它时:
# Setting model and delegate
macRangesModel = QSqlQueryModel()
macRangesModel.setQuery("select FIRST_MAC, ADDRESS_BLOCK_MASK from MacRanges")
macRangesModel.select()
self.initialMacComboBox.setModel(macRangesModel)
self.initialMacComboBox.setItemDelegate(MacAddressDelegate())
self.initialMacComboBox.setModelColumn(0)
它仅适用于下拉列表中的项目,但不适用于列表关闭时显示的默认项目(请注意,整数346868604928对应于MAC地址00:50:C2:FA:E0:00):
为什么会这样?我知道模型是否可编辑,默认值应显示在 QLineEdit 中,但事实并非如此,那么我们如何为已关闭的设置 QItemDelegate QComboBox 小部件?