我需要能够从ComboBox的内容中更新SQL记录。我正在使用tableview检索现有行并填充组合和qlinedit。
当我更改组合蛋白并尝试将其新状态写回数据库时,它们没有保存。我看不到代码中有任何明显的问题,但是对任何帮助都非常感谢。
示例代码:
// used to edit current database row
void Financelog::on_pushButton_Edit_clicked()
{
MainWindow conn;
QString BANK_MNTH, BUSN_MNGR, NEW_USED, APP_APPR;
BANK_MNTH=ui->txt_BANK_MNTH->text();
BUSN_MNGR=ui->txt_BUSN_MNGR->text();
NEW_USED=ui->comboBox_newused->currentText();
APP_APPR=ui->comboBox_approved->currentText();
if(!conn.connOpen()){
qDebug()<<"Failed to open database";
return;
}
QSqlQuery qry;
qry.prepare("update STOCK set BANK_MNTH='"+BANK_MNTH+"',BUSN_MNGR='"+BUSN_MNGR+"',NEW_USED='"+NEW_USED+"',APP_APPR='"+APP_APPR+"'");
if(qry.exec( ))
{
QMessageBox::critical(this,tr("Update"),tr("Record Updated"));
QSqlQueryModel * modal=new QSqlQueryModel();
QSqlQuery* qry2=new QSqlQuery(conn.mydb);
qry2->prepare("select top 100 DEAL_NUMB, BUSN_MNGR, BANK_MNTH, NEW_USED, APP_APPR");
qry2->exec();
modal->setQuery(*qry2);
ui->tableView->setModel(modal);
foreach(QLineEdit *Financelog, this->findChildren<QLineEdit*>()) {
Financelog->clear();
}
}
else
{
QMessageBox::critical(this,tr("Error"),qry.lastError().text());
}
}
// pre-fills Qlinedits when double clicking on the tableview index
void Financelog::on_tableView_activated(const QModelIndex &index)
{
QString val=ui->tableView->model()->data(index).toString();
MainWindow conn;
if(!conn.connOpen())
{
qDebug()<<"Failed to open database";
return;
}
QSqlQuery qry;
qry.prepare("select top 100 DEAL_NUMB, BANK_MNTH, BUSN_MNGR, NEW_USED, APP_APPR from STOCK where DEAL_NUMB ='"+val+"'");
if(qry.exec( ))
{
while(qry.next())
{
ui->txt_DEAL_NUMB->setText(qry.value(0).toString());
ui->txt_BANK_MNTH->setText(qry.value(1).toString());
ui->txt_BUSN_MNGR->setText(qry.value(2).toString());
ui->comboBox_approved->setCurrentText(qry.value(25).toString());
ui->comboBox_newused->setCurrentText(qry.value(28).toString());
}
}
else
{
QMessageBox::critical(this,tr("Error::"),qry.lastError().text());
}
}
在很好的情况下,您应该为表实现"委托",这将在表单元格中显示编辑器。这将是 qsyleditemdelegate class的孩子。您将通过qsyleditemdelegate :: setModeldata()方法保存数据。