PyQt6 Delegate class to show combo boxes in tableView cells, returns a strange value instead of an index into the combo values

I am adapting some working demo code that shows how to put combo boxes into tableView cells.
My problem concerns getting the wrong value returned from Delegate.setEditorData despite having the correct input args.
The working demo on which my code is based can be found here

I modified it for PyQt6 and it still works as a standalone demo.

Then I adapted my own code, which opens a dialog containing a tableview, two combo boxes and the usual Cancel-OK buttons. I am in the process of modifying the tableview to show combo boxes inside the cells so I can select the cells’ text contents. The ‘external’ combo boxes will then be redundant

Basically, the table shows bank statement narrations (text) that currently don’t have a category assigned to them; and a combo box will be used to select from about 20 categories (text).

A minor deviation is that I built the dialog using QtCreator, so I have a python class in a file called “ui_form.py” that contains a class “Ui_dialog()” that contains the “setupUI()” method that “builds” my gui. However this needs modifying if I need to put combo boxes into table cells. I did this by creating a new class called Ui that inherits from Ui_dialog, and calls setupUI() during its init phase. I hope that is the correct way to add bespoke functionality to the gui.

Now, the problem.
I created a Delegate class as in the demo
I have a Model which uses a pandas dataframe as the tableView data
The data shows correctly in the tableview
The combo boxes appear greyed in the correct tableView column
The combo boxes do not drop down when clicked
When the cell containing the combo box is double clicked, the program crashes in the setEditor method of the delegate because the value returned from ” value = index.data(Qt.ItemDataRole.DisplayRole)” is not an index into the combo data list
ERR: builtins.ValueError: 923.55 is not in list

import sys
from bank import *          # contains definition of BankData class
from ui_form import *       # contains QtCreator derived gui setup

from PyQt6.QtWidgets import QApplication, QDialog, QHeaderView
from PyQt6.QtCore import Qt, QAbstractTableModel

class Delegate(QtWidgets.QStyledItemDelegate): #combo box delegate
    def __init__(self, parent, choices):
        super().__init__()        
        self.items = choices
        
    def createEditor(self, parent, option, index):
        self.editor = QtWidgets.QComboBox(parent)
        self.editor.setEditable(True)
        self.editor.addItems(self.items)
        return self.editor
    
    def paint(self, painter, option, index):
        value = index.data(Qt.ItemDataRole.DisplayRole)
        style = QtWidgets.QApplication.style()
        opt = QtWidgets.QStyleOptionComboBox()
        opt.text = str(value)
        opt.rect = option.rect
        style.drawComplexControl(QtWidgets.QStyle.ComplexControl.CC_ComboBox, opt, painter)
        QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
        
    def setEditorData(self, editor, index):
        value = index.data(Qt.ItemDataRole.DisplayRole)
        num = self.items.index(value)
        editor.setCurrentIndex(num)
        
    def setModelData(self, editor, model, index):
        value = editor.currentText()
        model.setData(index, QtCore.QVariant(value), QtCore.Qt.ItemDataRole.DisplayRole)
        
    def updateEditorGeometry(self, editor, option, index):
        editor.setGeometry(option.rect)

class CategoriesModel(QAbstractTableModel):
    def __init__(self):
        super().__init__()
       
        self.account = BankData()          # create an instance of the BankData class
        df1 = pd.read_csv('testdata.csv')  # read in some test data 
        df2 =  self.account.categories     # careful - this does NOT copy the categories dataframe
        # cat_df is the dataframe being shown in the tableView
        self.cat_df = self.account.categorise(df1,df2)[1]  # unassigned categories dataframe
        self.categories_dict = df2.groupby('Category')['SubCategory'].unique().apply(list).to_dict()
        self.categoryList = list(self.categories_dict.keys())  # List of categories for combo

    def rowCount(self, parent=None):
        return len(self.cat_df)

    def columnCount(self, parent=None):
        return len(self.cat_df.columns)  # count of combo items

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if role == Qt.ItemDataRole.DisplayRole or role == Qt.ItemDataRole.EditRole:
            item =  self.cat_df.iloc[index.row()][index.column()]
            return item       

    def flags(self, index):
        return Qt.ItemFlag.ItemIsEditable | Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable
    
    def setData(self, index, value, role):
        if role == Qt.ItemDataRole.EditRole:
            self.cat_df.iloc[index.row(),index.column()] = value
        return True
    

class Ui(Ui_dialog):
    # subclass from Ui_dialog to enable adjustments to be made without editing Ui_dialog derived from QtCreator
    def __init__(self):
    
        self.dialog = QDialog()                     # create a standard dialog window
        Ui_dialog.setupUi(self, self.dialog)        # set up all the fruit configured by QtCreator
        self.model = CategoriesModel()              # Create a data model for Categories
        self.tableView.setModel(self.model)         # Attach the model to the tableview in the dialog
        self.tableView.setItemDelegateForColumn(4, Delegate(self.tableView, self.model.categoryList))
        #for row in range( self.model.rowCount()):
            #self.tableView.openPersistentEditor(self.model.index(row, 1))
        
        
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.catComboBox.addItems(self.model.categoryList)
        self.catComboBox.currentIndexChanged.connect( self.catComboBox_index_changed )
        
        
        
    def catComboBox_index_changed(self, index):
        self.model.subcategoryList = self.model.categories_dict[self.model.categoryList[index]]
        self.subCatComboBox.clear()        
        self.subCatComboBox.addItems(self.model.subcategoryList)        
        
    def subCatComboBox_index_changed(self, index):
        print(f"SubCat box index is {index}")
        
if __name__ == "__main__":

    a = QApplication(sys.argv)
    ui = Ui()                       # create an instance of the User Interface
    ui.dialog.show()                # show the dialog which is contained in the ui.
    a.exec()

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật