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