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に表示されるべきですが、そうではないので、閉じたQComboBoxウィジェットのQItemDelegateをどのように設定すればよいでしょうか?