Skip to main content
 首页 » 编程设计

python之为什么不能使用 QComboBox、QDataWidgetMapper 和 QSqlRelationalTableModel 进行编辑

2025年04月02日31mengfanrong

所以我正在构建 books Qt 文档中的示例,我无法使用组合框进行编辑。基本上,我有一个 QSqlRelationalTableModel 映射到 QTableView,并通过 QDataWidgetMapper 映射到其他几个控件(其中一个是组合框)。 TableView 和映射器都使用默认的 QSqlRelationalDelegate。默认委托(delegate)启用编辑,即使对于作为其他表的外键的字段也是如此 - 它会在表上创建一个组合框。

我可以在表格中编辑任何我想要的东西,而且效果很好。我还可以使用通过小部件映射器映射的控件进行编辑,使用组合框除外。组合框正确填充,并在我更改表中的选择时正确更新,但更改它的值对模型没有影响。然而,直接在表中进行编辑(使用由 QSqlRelationalDelegate 创建的组合框)确实有效。

通过阅读示例和文档,这似乎应该 可行。我什至尝试过实现自定义委托(delegate),但是在对组合框进行更改时甚至从未调用过它的 setModelData() 方法(为什么不呢?)。

有没有人遇到过这个问题?你是怎么解决的?我觉得我一定错过了一些明显的东西。以下代码的相关部分:

# Create the model 
self.model = QSqlRelationTableModel(self.tableView) 
self.model.setEditStrategy(QSqlTableModel.OnManualSubmit) 
self.model.setTable('products') 
 
categoryIdx = self.model.fieldIndex('category') 
 
# Set the relation for the category field 
self.model.setRelation(categoryIdx, QSqlRelation('categories', 'id', 'name')) 
 
# Populate the model 
self.model.select() 
 
# Connect the model and the table 
self.tableView.setModel(self.model) 
self.tableView.setItemDelegate(QSqlRelationalDelegate(self)) 
 
# Set up the controls 
self.categoryBox.setModel(self.model.relationModel(categoryIdx)) 
self.categoryBox.setModelColumn(self.model.relationModel(categoryIdx).fieldIndex('name') 
 
mapper = QDataWidgetMapper(self) 
mapper.setModel(self.model) 
mapper.setItemDelegate(QSqlRelationalDelegate(self)) 
mapper.addMapping(self.categoryBox, categoryIdx) 
... # Add mappings to the other controls 
mapper.setSubmitPolicy(QDataWidgetMapper.AutoSubmit) 
 
self.tableView.selectionModel().currentRowChanged.connect(mapper.setCurrentModelIndex) 

我什至试过像这样指定 currentIndex 属性:

mapper.addMapping(self.categoryBox, categoryIdx, 'currentIndex') 

但这也行不通。我正在使用 PyQt5,FWIW。

请您参考如下方法:

非常感谢 Garrett 和 Georg Schölly 发表的这些文章!我也遇到了同样的问题,可以通过您的回答解决。在我的例子中,我创建了一个 QDataWidgetMapper 子类,它可以自动建立所需的信号槽连接:

class DataWidgetMapper(QDataWidgetMapper): 
    def addMapping(self, widget, section, propertyName=None): 
        if propertyName is None: 
            super().addMapping(widget, section) 
        else: 
            super().addMapping(widget, section, propertyName) 
 
        if isinstance(widget, QComboBox): 
            delegate = self.itemDelegate() 
            widget.currentIndexChanged.connect(lambda: delegate.commitData.emit(widget))