I'm using PyQt5 and trying to create a GUI with a list of some custom data structure (Recipe), and I defined a custom widget as a subclass of QWidget that describes how it should be displayed.
I am trying to use MVC so I have a QListView and I subclassed QAbstractListModel.
I want the list to contain my custom widget instead of just text, so I also defined an item delegate for it that returns that widget. Perhaps my understanding of exactly how these three components (model, item delegate, view) work together is flawed, because I'm not sure how to access whatever is returned from the data() method of the model and turn that into the particular widget I want to display in that list cell.
Example code:
class Recipe:
pass # custom data structure
class RecipeWidget(QWidget, RecipeWidgetUI):
def __init__(self, recipe, *args, **kwargs):
super(RecipeWidget, self).__init__(*args, **kwargs)
self.recipe = recipe
self.setupUi(self)
# some code here to populate the UI elements with data from self.recipe
class RecipeListModel(QAbstractListModel):
def __init__(self, recipes, *args, **kwargs):
super(RecipeListModel, self).__init__(*args, **kwargs)
self.recipes = recipes
def rowCount(self, index):
return len(self.recipes)
def data(self, index, role):
if role == Qt.DisplayRole:
return str(self.recipes[index.row()]) # this is the part I'm confused about
class RecipeItemDelegate(QItemDelegate):
def __init__(self, parent):
QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
return RecipeWidget(recipe, parent=parent) # where do I get recipe from??
class MainWindow(...):
def __init__(self, ...):
...
self.model = RecipeListModel(recipes)
self.listView.setModel(self.model)
self.listView.setItemDelegate(RecipeItemDelegate(self.listView))
I know the data(...) function in the model is supposed to return a string; what I don't understand is:
- How do I instead return my
Recipedata structure? Do I have to serialize it somehow and then deserialize later? - Where does
RecipeItemDelegatesee what was returned by thedata(...)function in order to properly construct the recipe object?