Reputation: 6651
I am mostly a Python/Django developer, so I might be a little off in the terminology, so I can't find answer to this question:
How/where should I define custom model logic in C++/Qt?
Let say I have table Users
with column date_birth
and I want to add method getAge()
, which simply calculate user's age.
Where would I put this? Creating a subclass of QSqlRecord seems to me appropriate, but I haven't found any references to this approach.
Second: Are there any conventions for subclassing QSql(Relational)?TableModel?
I've found similar snippet in many examples:
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("employee");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
but it seems redundant to define it everywhere I need it. Is it common to create subclasses such as UserTableModel and call all these methods in it's constructor? Again, I haven't found any references to it.
Upvotes: 1
Views: 573
Reputation: 772
May I offer you another approach where instead of the inheritance you will use proxy model to separate logic from data sources.
That method looks more flexible and more robust to changes of layout how the data are defined. There are some set of articles which can give more good hints how to use models in very flexible ways:
http://lynxline.com/category/models/
Upvotes: 0
Reputation: 5776
To Create your own model in Qt you should
1. Create a class wihich Inherits QSqlTableModel
2. Implement if neded:
QVariant data( const QModelIndex& index, int role = Qt::DisplayRole ) const;
int rowCount( const QModelIndex& parent = QModelIndex() ) const;
3. Add any method you want.
more info you can find here
Upvotes: 0
Reputation: 1682
What you are trying to achieve is an objets/relational mapping.
So do it, it's better not to make objects inherit from any SQL classes (in any object language)
You may create 2 classes: one for your "employee" and a factory object which will create this object by dealing with SQL ones:
ObjectsFactory *factory = new ObjectsFactory();
Employee e = factory->getEmployee(2423);
int age = e->getAge();
With this kind of solution, your Employee class won't depend on SQL classes. You can even chose to create handlers depending on any storage model.
ObjectFactory *factory = new ObjectsFactory(new SQLHandler);
or (more convenient for testing)
ObjectFactory *factory = new ObjectsFactory(new FileHandler);
ObjectFactory *factory = new ObjectsFactory(new MemoryHandler);
I suggest you have a look at Data Access Object pattern
Upvotes: 1