2

我有两个具有以下结构的 SQLite 表:

CREATE TABLE "log" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name"  TEXT,
    "value" INTEGER NOT NULL,
    "category_id"   INTEGER NOT NULL,
    "date"  TEXT NOT NULL,
    FOREIGN KEY("category_id") REFERENCES "category"("id")
);

CREATE TABLE "category" (
    "id"    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    "category_name" TEXT NOT NULL,
    "type"  TEXT NOT NULL
);

我还想显示QTableView使用 a 的 a QSqlRelationalTableModel。我需要显示两列 (category_nametype) 而不是category_id,尽管QSqlRelation似乎只用一列替换了外键,但我设法显示了 2 列,如下所示:

self.balance_table_model = QSqlRelationalTableModel()
self.balance_table_model.setTable("log")
self.balance_table_model.setRelation(3, QSqlRelation("category", "id", "category_name, type"))
self.balance_table_model.setHeaderData(1, Qt.Horizontal, "Name")
self.balance_table_model.setHeaderData(2, Qt.Horizontal, "Value")
self.balance_table_model.setHeaderData(3, Qt.Horizontal, "Category")
self.balance_table_model.setHeaderData(4, Qt.Horizontal, "Type")
self.balance_table_model.setHeaderData(5, Qt.Horizontal, "Date")
self._ui.balanceTableView.setModel(self.balance_table_model)
self._ui.balanceTableView.setColumnHidden(0, True)

现在,当我想添加一个新行时,只有当我加入没有类型的两个表时,插入才有效,即

self.balance_table_model.setRelation(3, QSqlRelation("category", "id", "category_name"))

插入代码:

record = self.balance_table_model.record()
record.setGenerated(0, True)
record.setValue(1, log_name)
record.setValue(2, log_value)
record.setValue(3, category_id)
record.setValue(4, date)
self.balance_table_model.insertRecord(-1, record)

如何在仍然能够显示type列的同时使插入工作?

4

0 回答 0