QSqlTableModel in QML
-
Most of the logics of my app is in Qt/C++, but I'm using QML for the UI.
I need to read a QSqlTableModel and create a ListView on the QML side which loads all its content. So far the only solution I found is creating an intermediate table subclasing QStandardItemModel where I need to define one additional role per column in my table where I will store my data to expose to QML and make it available in my UI.
Is there any possibility to read columns from a QSqlTableModel directly? or the QML side only understand roles?
I think this is a serious issue. The amount of overhead for an operation like this is no sence.
A simple line in Qt/C++ like:@myTableView->setModel(myTableModel)@
Turns to be a ton of work in QML.
-
I have been working out on a simple solution for this limitation and I'm sharing a fearly small and simple code that do the job nicely.
I'm sure it will be useful for others using QAbstractItemModel subclasses:
@
class ProxySqlTableModel : public QSqlTableModel
{
Q_OBJECT
public:
explicit ProxySqlTableModel(QObject *pObject = 0);
QVariant data (const QModelIndex & Index, int iRole = Qt::DisplayRole) const;
void setProxyModel(const QString& sTable);
};ProxySqlTableModel::ProxySqlTableModel(QObject *pObject) :
QSqlTableModel(pObject)
{
}QVariant ProxySqlTableModel::data (const QModelIndex & Index, int iRole) const
{
if (iRole>=Qt::UserRole)
return QSqlTableModel::data(index(Index.row(),iRole-Qt::UserRole));return QSqlTableModel::data(Index,iRole);
}void ProxySqlTableModel::setProxyModel(const QString& sTable)
{
QHash<int, QByteArray> hashRoles;QSqlTableModel Table;
Table.setTable(sTable);
QSqlRecord Record=Table.record();for (int i=0; i<Record.count(); i++)
hashRoles.insert(Qt::UserRole+i,Record.fieldName(i).toAscii());
setRoleNames(hashRoles);
setTable(sTable);
select();
}
@ -
I have the same issue, not happy with the design of Model/View with QML. It seems that only very basic use cases are possible without tons of workarounds.
Model/View was a pain using plain Qt, it is even worse now with QML.
Thanks for your input, I will try this.