gpt4 book ai didi

c++ - 将行插入 QSqlTableModel

转载 作者:行者123 更新时间:2023-11-28 01:40:34 26 4
gpt4 key购买 nike

当一行要被编辑时,一个索引被传递到编辑对话框中。
编辑工作正常。
当我想添加一行时,我没有将索引传递给对话构造函数,因此它知道它应该添加一个新行。
这是对对话按钮使用react的函数代码

void DialogAddCl::on_buttonBox_clicked(QAbstractButton *button)
{
// prepare
m->database().transaction();
QString debugstr;
auto chi4 = ui->buttonBox->buttonRole(button);
int rowCount = m->rowCount();
switch (chi4) {
case QDialogButtonBox::AcceptRole:
if (!ind->isValid())
// insert
if (!m->insertRow(rowCount, *ind))
{
QMessageBox::critical (this, "Error inserting into model", m->lastError().text(), QMessageBox::Cancel);
break;
}
else
{
m->setData(m->index(rowCount, 0), rowCount+1);
}
else
{
// update
rowCount = ind->row();
}
m->setData(m->index(rowCount, 1), ui->name->text());
m->setData(m->index(rowCount, 2), ui->addr->text());
// 12 other setData() calls

if (m->submitAll())
{
m->database().commit();
}
else
{
// rollback if error
m->database().rollback();
debugstr = QString(m->database().lastError().text());
QMessageBox::critical (this, "Database returned an error",
m->database().lastError().text(), QMessageBox::Cancel);
}
case QDialogButtonBox::RejectRole:
this->close();
break;
case QDialogButtonBox::ResetRole:
fillFields();
break;
default:
break;
}

}

这是一段dialogaddcl.h:

private:
Ui::DialogAddCl *ui;
QSqlTableModel* m;
QModelIndex* ind;

因此,如果我编辑现有记录,m->submitAll() 工作正常,如果我尝试提交新插入的行,则失败。我已经通过调试检查过,setData() 调用即使在添加时也能正常工作,所以它不是 DB 期望 NOT NULL 字段并给出错误。
顺便说一句,也许有人可以指出一种捕获实际错误文本的方法?我尝试使用 debugstr,但它始终只包含空字符串。我打印的错误信息也是如此

最佳答案

要向 QSqlTableModel 插入一行,你不应该直接使用 setData(),如果你不能使用 insertRecord(),你在哪里指示行和 QSqlRecordQSqlRecord可以通过模型的record()方法获取。

InsertDialog dial;
if(dial.exec()== InsertDialog::Accepted){
db.transaction();
QString f = dial.firstname();
QString l = dial.lastname();

QSqlRecord record = model.record();
/* since the id field has the autoincrement attribute,
* it is not necessary to indicate its value,
* that is because this field of the request is removed.
*/
record.remove(record.indexOf("id"))
record.setValue("firstname", f);
record.setValue("lastname", l);
/*-1 is set to indicate that it will be added to the last row*/
if(model.insertRecord(-1, record)){
qDebug()<<"successful insertion";
model->submitAll();
}
else{
db.rollback();
}
}

在下面link你会找到一个例子。

关于c++ - 将行插入 QSqlTableModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com