【发布时间】:2020-09-30 11:47:36
【问题描述】:
我正在使用 PyQt5 并尝试使用一些自定义数据结构 (Recipe) 的列表创建一个 GUI,并且我将自定义小部件定义为 QWidget 的子类,它描述了它应该如何显示。
我正在尝试使用 MVC,所以我有一个 QListView 并且我将 QAbstractListModel 子类化。
我希望列表包含我的自定义小部件而不仅仅是文本,因此我还为其定义了一个返回该小部件的项目委托。也许我对这三个组件(模型、项目委托、视图)如何协同工作的理解存在缺陷,因为我不确定如何访问模型的 data() 方法返回的任何内容并将其转换为特定的小部件我想在该列表单元格中显示。
示例代码:
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))
我知道模型中的data(...) 函数应该返回一个字符串;我不明白的是:
- 如何改为返回我的
Recipe数据结构?我是否必须以某种方式对其进行序列化,然后再反序列化? -
RecipeItemDelegate在哪里查看data(...)函数返回的内容以便正确构造配方对象?
【问题讨论】:
-
我不确定我是否理解您的问题。可以使用
index.data(role)访问项目数据,您可以通过使用index.data()添加关键字参数来填充createEditor 中的RecipeWidget,或者更好的是使用setEditorData()。
标签: python user-interface model-view-controller pyqt5