问题描述
我为使用 qml 编写了 QSQLTableModel 继承器,它运行良好.我也需要将它与 QTableView 一起使用,数据显示,但我无法修改它 - 当我编辑一切正常时,但当我离开现场时所有更改都会下降(我知道 editStrategy,但问题发生得更早).我想虚函数有问题,但我无法理解是什么.如果我使用相同的参数创建 QSqlTableModel,一切都很好.有人知道我该如何解决这个问题?我的代码:
I wrote QSQLTableModel inheritor for working with qml and it's work well. I need use it with QTableView too, data shows, but I cannot modify it - when I edit everything is ok, but all changes drop when I get out from field (I know about editStrategy, but the problem occurs earlier). I suppose that something wrong with virtual function, but I cant undestant what. If i create QSqlTableModel with the same parameters, everything is ok. Somebody have any idea how can i fix this? My code:
h:
class ListModel : public QSqlTableModel
{
Q_OBJECT
Q_PROPERTY( int count READ rowCount() NOTIFY countChanged())
signals:
void countChanged();
public:
Q_INVOKABLE QVariant data(const QModelIndex &index, int role) const;
ListModel(QObject *parent, QSqlDatabase _db):QSqlTableModel(parent,_db){this->setEditStrategy(QSqlTableModel::OnManualSubmit);}
void applyRoles();
#ifdef HAVE_QT5
virtual QHash<int, QByteArray> roleNames() const{return roles;}
#endif
private:
int count;
QHash<int, QByteArray> roles;
};
cpp:
//based on http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML
void ListModel::applyRoles()
{
roles.clear();
qDebug()<<"\n"<<this->tableName();
for (int i = 0; i < this->columnCount(); i++) {
QString role=this->headerData(i, Qt::Horizontal).toString();
roles[Qt::UserRole + i + 1] = QVariant(role).toByteArray();
qDebug()<<this->headerData(i, Qt::Horizontal);
}
#ifndef HAVE_QT5
setRoleNames(roles);
#endif
}
QVariant ListModel::data(const QModelIndex &index, int role) const{
QVariant value;
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);
}
else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
UPD我知道问题出在 data
方法的量词 const 中,如果我删除它,QTableView 一切正常,但我无法从带有 gml 列表视图的模型中获取数据.我只看到一个解决方案 - 用聚合替换 QSqlTableModel 中的中断,但也许有人知道更好的解决方案?
UPDI understood that the problem is in data
method's quantifier const, if I remove it everything is ok with QTableView, but I cant get data from model with gml's listviews. I see only one solution - replace interition from QSqlTableModel with aggregation it, but maybe someone knows better solution?
推荐答案
总结:用奇怪的hack解决——继承自QSqlRelationalTableModel而不是QSqlTableModel,我认为原因是QSqlRelationalTableModel重写了非虚方法数据
Summary: Solved with strange hack - inherited from QSqlRelationalTableModel instead QSqlTableModel, I think the reason is that QSqlRelationalTableModel has rewritten non virtual method data
这篇关于QSQLTableModel 继承者和 QTableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!