我正在使用 QComboBox 将来自数据库的一些 MAC 地址显示为整数。为了以更熟悉的“dotted octets”格式显示它们,我创建了以下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中,但事实并非如此,那么我们如何为关闭的QComboBox小部件设置QItemDelegate呢?