How to clear/remove ComboBox delegate data from QTableView

Heads up! You've already completed this tutorial.

Amit_Khanna | 2021-04-15 20:54:49 UTC | #1

Hi Guys,

Can someone please help with this issue? I have a table view with QtCore.QAbstractTableModel and a ComboBox delegate using QItemDelegate. Displaying data is working fine except when my data changes the numbers in delegate don't change and get stuck to what it populated on the first run of receiving data.

How can I clear the items in the ComboBox delegate? I have tried re instantiating the delegate but didn't help, I even tried just deleting and re-adding it, still keeps the same data.

In my logger, I see the new data getting applied to the model!

I am adding the delegate like this:

python
delegate = mv.ComboDelegate(self)
self.ui.table_view.setItemDelegateForColumn(col_id, delegate)

and this is the delegate class

python
class ComboDelegate(QItemDelegate):
    """
    A delegate to add QComboBox in every cell of the given column
    """

    def __init__(self, parent):
        super(ComboDelegate, self).__init__(parent)
        self.model = None
        self.parent = parent

    def createEditor(self, parent, option, index):
        combobox = QComboBox(parent)
        version_list = []
        for item in index.data():
            if item not in version_list:
                version_list.append(item)
        combobox.addItems(version_list)
        combobox.currentTextChanged.connect(lambda value: self.currentIndexChanged(index, value))
        return combobox

    def setEditorData(self, editor, index):
        value = index.data()
        if value:
            maxval = len(value)
            editor.setCurrentIndex(maxval - 1)

    def setModelData(self, editor, model, index):
        # model.setData(index, editor.currentText())
        # print editor.currentText()
        # model.setData(index, editor.currentIndex())
        pass

    def currentIndexChanged(self, index, value):
        self.parent._table_view_selection_changed()

Amit_Khanna | 2021-04-15 21:16:12 UTC | #2

Dammit found the answer right after posting... The model needed the data reset:

python
  self.table_model.beginResetModel()
  self.table_model.endResetModel()

martin | 2021-04-16 11:43:08 UTC | #3

Thanks for posting the solution @Amit_Khanna it'll help other people with the same question!


Over 10,000 developers have bought Create GUI Applications with Python & Qt!

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount with the code [[ couponCode ]] — Enjoy!

For [[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount with the code [[ couponCode ]] — Enjoy!

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak