PDA

View Full Version : Adding new record to database from QDataWidgetMapper



naptizaN
12th July 2012, 21:05
Hello, i am trying to make a small database redactor with QDataWidgetMapper as edit field for data and qtableview. Pressing button "add new parameter" must add a new record to model with current data from QDataWidgetMapper. Currentrly a managed to add an empty record in the end af model. How must i do it and what is the best way?
Adding some source code with model and mapper:


filterModel = new QSortFilterProxyModel;
filterModel->setSourceModel(modelt);
filterModel->setFilterKeyColumn(2);
mapper = new QDataWidgetMapper(this);
mapper->setModel(filterModel);
mapper->addMapping(le1, 2);
mapper->addMapping(le2, 1);
mapper->addMapping(le3, 3);
mapper->addMapping(le4, 5);
mapper->addMapping(le5, 6);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
......
QPushButton* pcmd3 = new QPushButton("Add new parameter");
pcmd3->setIcon(QIcon(":/icons/16x16/actions/add.png"));
connect(pcmd3, SIGNAL(clicked()), this, SLOT(insertRow()));
and slot:

void MainWindow::insertRow()
{
filterModel->insertRow(filterModel->rowCount());
mapper->toLast();
mapper->submit();
}

ChrisW67
13th July 2012, 00:24
The "current data from QDataWidgetMapper" belongs to another row in the table. Your code creates a new 'blank' row in the model and positions the mapper there, causing it to display the new 'blank' row. If you want to duplicate the original row in the model into the new row then you should code it to do so. I don't really see the problem here.

naptizaN
13th July 2012, 06:50
Mapper is connected with tableview:

connect(view->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)) , mapper, SLOT(setCurrentModelIndex(QModelIndex)));
I meant that i select some row in view, mapper displays it, i make some changes in lineedits without submitting and press "add new parameter", and it creates a new record in model with new data from mapper.

ChrisW67
13th July 2012, 07:18
Yes. If you want to create a new row in the model containing the current values in the widgets the QDataWidgetMapper is also using then write some code to do that. Your current code does not and QDataWidgetMapper will not magically do it for you.

naptizaN
15th July 2012, 13:19
Made in such way. But how can i place mapper on it and update tableview to display new record?



void MainWindow::insertRow()
{
QSqlDatabase db=QSqlDatabase::database();

QString sqlstr=QString("INSERT INTO sianimtable (CIPHER,CIPHERKP,TITLE,MSGON,MSGOFF) VALUES(\"%1\",\"%2\",\"%3\",\"%4\",\"%5\");")
.arg(le2->text())
.arg(le1->text())
.arg(le3->text())
.arg(le4->text())
.arg(le5->text());


QSqlQuery q(db);
if(q.exec(sqlstr)==false)
{
QMessageBox *pmsg = new QMessageBox;
pmsg->setText("Не могу соединиться с базой данных");
pmsg->setInformativeText(q.lastError().text());
pmsg->exec();
return;
}