[Interest] Best way to implement "delete from" when using a QSqlTableModel?

K. Frank kfrank29.c at gmail.com
Sun Jul 8 16:55:49 CEST 2012

Hello Guenther!

On Sun, Jul 8, 2012 at 8:11 AM, Guenther Boelter <gboelter at gmail.com> wrote:
> On 07/08/2012 12:45 AM, K. Frank wrote:
>> I have a QSqlTableModel (connected to a QTableView) that I use
>> to edit a table in a database.
>> Specifically, I would like to achieve the effect of:
>>    delete from my_table where my_column = 'some_value';
>> I don't see a way to do this directly with QSqlTableModel.  Have I
>> missed anything?
>> I see two possibilities:
>> First, I could identify the rows I wish to delete (e.g., by running a
>> select query), and then call QSqlTableModel::removeRows on the
>> rows in question.
>> Second, I could run "delete from" on the database, and then tell
>> QSqlTableModel to resynchronize itself with its underlying table.
>> ...
> Hi Frank,
> why not 'bool QSqlTableModel::removeRows ( int row, int count, const
> QModelIndex & parent = QModelIndex() )'?

Yes, that's one of the methods I am thinking about.  But I still have
to identify the rows to delete (and identify their location in the
QSqlTableModel).  I could run an independent select (separate from
the QSqlTableModel), but then I have to somehow find the selected
rows in the QSqlTableModel.  Or I could iterate through the rows
in the QSqlTableModel, identify by hand those that match my where
clause, and delete them.  But that seems like I would be reinventing
the "delete from .. where ..." wheel.

Another approach I'm thinking about (but haven't tried yet) is to set
a filter on the QSqlTableModel that corresponds to the where clause
of my sql delete statement:

   model->setFilter ("my_column = 'some_value'");

delete all the rows in the (filtered) QSqlTableModel, and then restore
the unfiltered QSqlTableModel by removing the filter (presumably by
setting an empty filter with a empty/null QString, setFilter (QString());).

> Regards
> Guenther

Thanks for your thoughts.

K. Frank

More information about the Interest mailing list