【发布时间】:2018-04-29 08:07:53
【问题描述】:
当要编辑一行时,会将索引传递到编辑对话框中。
编辑工作正常。
当我想添加一行时,我不会将索引传递给对话构造函数,因此它知道它应该添加一个新行。
这是对对话按钮做出反应的函数代码
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,但它总是只包含空字符串。我打印的错误消息也是如此
【问题讨论】:
标签: c++ qt qt5 qtsql qsqltablemodel