pyqt关系table更新外键时不更新

pyqt relational table not updating when foreign key is updated

我有一个带分离器的 window,在两个框架内有两个不同的表,产品类型与产品有关系,GUI 运行和工作正常,但是当我更改名称时product type 它没有在 product 表上更新,这是为什么?但是一旦我重新启动更改就完成了吗?有没有办法强制 pyqt 模型检查数据库的变化?

def initUI(self):

        self.connectDb()

        mainlayout = QtGui.QVBoxLayout(self)
        self.mode = QtGui.QAbstractItemView.SingleSelection

        self.topleft = QtGui.QFrame(self)
        self.topleft.setFrameShape(QtGui.QFrame.StyledPanel)
        self.topleftfill()
        self.topright = QtGui.QFrame(self)
        self.topright.setFrameShape(QtGui.QFrame.StyledPanel)
        self.toprightfill()

        splittertop = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splittertop.addWidget(self.topleft)
        splittertop.addWidget(self.topright)
        mainlayout.addWidget(splittertop)
        self.setLayout(mainlayout)

def topleftfill(self):
    layout = QtGui.QVBoxLayout(self)
    model = QtSql.QSqlRelationalTableModel()
    model.setTable("Product")
    model.setRelation(6, QtSql.QSqlRelation("ProductType","ProductTypeID","Type"))
    model.select()
    model.setHeaderData(0, QtCore.Qt.Horizontal, "Product ID")
    model.setHeaderData(1, QtCore.Qt.Horizontal, "Product Name")
    model.setHeaderData(2, QtCore.Qt.Horizontal, "In Stock ")
    model.setHeaderData(3, QtCore.Qt.Horizontal, "Expiry Date")
    model.setHeaderData(4, QtCore.Qt.Horizontal, "Stock Alert")
    model.setHeaderData(5, QtCore.Qt.Horizontal, "Price")
    model.setHeaderData(6, QtCore.Qt.Horizontal, "Product Type")
    edit = QtSql.QSqlTableModel.OnFieldChange
    model.setEditStrategy(edit)
    view = QtGui.QTableView()
    view.setModel(model)
    view.setSelectionMode(self.mode)
    view.setItemDelegate(QtSql.QSqlRelationalDelegate(view))
    layout.addWidget(view)
    self.topleft.setLayout(layout)

def toprightfill(self):
    layout = QtGui.QVBoxLayout(self)
    model = QtSql.QSqlRelationalTableModel()
    model.setTable("ProductType")
    model.select()
    model.setHeaderData(0, QtCore.Qt.Horizontal, "Product Type ID")
    model.setHeaderData(1, QtCore.Qt.Horizontal, "Product Type")
    edit = QtSql.QSqlTableModel.OnFieldChange
    model.setEditStrategy(edit)
    view = QtGui.QTableView()
    view.setModel(model)
    view.setSelectionMode(self.mode)
    layout.addWidget(view)
    self.topright.setLayout(layout)


def connectDb(self):
    name = 'PostOffice.db'
    initDb.setup_database(name)
    db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName(name)
    if not db.open():
        print("Cannot Connect")
        return False    

问题是,如果您使用 OnManualSubmit 编辑策略,按下按钮编辑更改后,您需要确保通过调用 model.select() 函数重新填充 table否则程序将使用您的旧模型,直到您重新启动程序