PDA

View Full Version : [Qt] TableView and QSqlQueryModel



Xandareva
6th April 2010, 18:03
Hello,
It's me again ^^ and of course I have a problem. So.. I don't know how to delete records from tableView and QSqlQueryModel. I know how get number of row which is seleted but I don't know what do after. All is ok but if I want to delete a record from tableView (and from database) then I don't know how can I do it. Now I have written add button which add new record and refresh table but I don't know how to write delete button which delete selected row.

tableView looks like:

Header: ID | NAME
1 | 23 | ASDF
2 | 52 | FDGDR

So I want to get value from column ID or something to delete row from database.

waynew
6th April 2010, 23:03
QSqlQueryModel is read only. You can't do dml operations with it.
Use QSqlTableModel instead.

JD2000
7th April 2010, 09:35
You can run a sql delete query to delete the underlying records in the database and then refresh your model.

Xandareva
7th April 2010, 13:08
@JD2000 yes I have this idea too but I don't know how to get value of currently selected item ;)

JD2000
7th April 2010, 14:12
The sql delete command has much the same syntax as a select query.

Assuming that your table has a primary key (ID) as the first element on each row, you could try something like



QString ID = model->data(model->index(TableView->selectionModel()->currentIndex().row(),0)).toString();
QSqlQuery query;
query.prepare("SELECT FROM table WHERE id = ?"); // or SELECT * FROM
query.addBindValue(ID);
query.exec();


Once you are happy that the correct row is being selected for deletion, substitute DELETE for SELECT in the above query. Please note I have not tested this but in theory it should work.

There is probably a more elegant way to do this, I'll leave that to you!

Xandareva
7th April 2010, 14:20
thx :) it works ;-)