![](/img/trans.png)
[英]How to prevent from inserting new row when item is dropped with QTableWidget in PySide
[英]QSqlTableModel.insertRecord(row, record) not inserting at specified row
使用此处提供的答案,我能够将记录插入到我的 QSqlTableModel 中。 虽然这会将记录附加到末尾(行 = -1)就好了,但更改行不会更改插入记录的位置。 如何在指定行插入记录?
import sys
from PySide6.QtWidgets import (QApplication, QMainWindow, QTableView)
from PySide6.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
class SQLTableModel(QSqlTableModel):
def __init__(self, parent=None):
super().__init__(parent)
query = QSqlQuery()
query.exec(
"CREATE TABLE table1"
"(id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, "
"type TEXT)"
)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.db = QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName("SQLTableDatabase.sqlite")
self.db.open()
self.table_view = QTableView()
self.model = SQLTableModel()
self.table_view.setModel(self.model)
self.model.setTable("table1")
for i in range(4):
record = self.model.record()
record.setValue("type", str(i))
self.model.insertRecord(-1, record)
record = self.model.record()
record.setValue("type", "TEST")
self.model.insertRecord(2, record) # Why is this record not inserted at row 2?
self.model.select()
self.setCentralWidget(self.table_view)
app = QApplication(sys.argv)
mainwindow = MainWindow()
mainwindow.show()
sys.exit(app.exec())
由于它们的性质,数据库没有在给定索引处插入的概念:记录总是附加的。
默认的editStrategy
(指示模型何时将更改实际提交到数据库)是OnRowChange
,并且每当插入新记录时也会发生这种情况。
结果是当你到达for循环的末尾时,模型已经提交了更改并且新记录已经插入,所以无论你使用什么row
,数据库都只能在末尾插入新记录。
在给定行中插入记录的唯一(简单)方法是在先前已插入但尚未提交的情况下执行此操作,并使用OnManualSubmit
策略。
在你的情况下:
class MainWindow(QMainWindow):
def __init__(self):
# ...
self.model = SQLTableModel()
self.model.setTable("table1")
self.model.setEditStrategy(self.model.OnManualSubmit)
# ...
self.model.insertRecord(2, record)
self.model.submitAll()
self.model.select()
self.model.setEditStrategy(self.model.OnRowChange)
这将在第 2 行正确插入最后一条记录。
但是,如果以前的记录已经存在于数据库中(或以前提交过),那么您无能为力,除了重新生成表,或手动UPDATE
从所需行开始的所有记录,通过“移动”每个记录的现有数据记录到下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.