1

I am using a QComboBox to display some MAC addresses which come from a database as integer numbers. For displaying them in the more familiar "dotted octets" format, I created the following 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)

but when I set the model from a QSqlTableModel and the QComboBox delegate to it:

    # 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)

it works only for the items in the dropdown list, but not for the default item shown with the list closed (note that integer 346868604928 corresponds to the MAC address 00:50:C2:FA:E0:00):

enter image description here

Why is that happening? I know if the model was editable the default value should be shown in a QLineEdit, but that's not the case, so how do we set the QItemDelegate for the closed QComboBox widget?

Claudio
  • 2,191
  • 24
  • 49

0 Answers0