3

I have a QSqlTableModel and I want to insert and update records in it with a special form in a child-window. It's a design choice not to allow "inline editing" which I disabled on purpose.

When the user selects an entry (which can be sorted and filtered through a QSortFilterProxyModel and is presented through a QTableView), he has three options (represented by buttons): delete, edit and add.

My problem is with editing:

  1. The parent-widget emits a signal with a given record and executes a model child-view
  2. The child-widget prepares a form based on the record, waits for user input, validates it, creates a record and sends it back to the parent-widget.
  3. The parent-widget takes the record and puts it into the database.

And right here is the problem! One can get the right record by row quite easily, like so:

void Parent::on_button_edit_record_clicked()
{
    // Table could be sorted/filtered!
    row = proxyModel->mapToSource(ui->tableView->currentIndex()).row();
    QSqlRecord r = model->record(row);

    emit editRecordSignal(record);
    child->exec();
}

void Parent::editRecord(const QSqlRecord &record)
{
    model->setRecord(row, record);
}

As you can see, I manually save the row of the record I want to update. I don't think this is a nice way to handle this. Actually it seems rather hacky to me.

What I missed was an easy way to translate a primary key to a row and vice versa. Like:

void Parent::editRecord(const QSqlRecord &record)
{
    model->setRecord(model->primaryKeyToRow(record->value("id")), record);
}

Is there any way to easily do this (without having to extend the QSqlTableModel), so did I miss something or do I really need to save the row manually to achieve what I want?

msrd0
  • 7,816
  • 9
  • 47
  • 82

0 Answers0