PDA

View Full Version : retrieve QSqlTableModel from QTableView?



jtdavidson
16th July 2010, 07:04
I have a QTableView that gets assigned its QSqlTableModel in a function.
Later, I need to access that QSqlTableModel, but the function which created it has passed out of scope. As far as I understand it (which is not very far, because I am starting to get confused by all of this) the only thing that is still in scope for me is the QTableView, which I access via ui->QTableView.
Is it possible to get access to the original QSqlTableModel via the QTableView? I have tried
QSqlTableModel *newModel = ui->QTableView->model()
but that doesn't seem to get me my QSqlTableModel. ui->QTableView->model() returns a QAbstractItemModel rather than a QSqlTableModel.
What should I do? Should I just declare the original QSqlTableModel as global? It's just a pointer, but even so, isn't that bad form in objected oriented programming?

My goal is actually quite simple: all I want to do is get the data from the selected row in the QTableView. I know how to get the rowid of the selected row, but I don't know how to get the data once i have the rowid. I think I need the model->record(rowid)->field(), but to get at the record I think I need the QSqlTableModel.

As you can see, I am tying myself up in knots! I'm new to object oriented programming and QT.

Any advice (other than the obvious advice that I should stick to the shallow end of the pool)?

thanks in advance

John

tbscope
16th July 2010, 08:41
model() does return the QSqlTableModel, but not directly. It would be impossible to create a list of functions that return everything and the kitchen sink. The model() function returns the most common baseclass of a model, and that's an abstract class.

Therefor there's a technique called casting. You need to tell the compiler that it's not an abstract class but a QSqlTableModel via a cast.

However, casting is ugly and can lead to unexpected and difficult to find errors. Therefor it's much better to not do any casting at all.
And that's why you are very close when you say that the model needs to be defined globally. This means you want to define your model at the same place you define your view.

Example:


MyClass
{
Private:
QTableView *view;
QSqlTableModel *model;
};

Then the model is available in the complete class.