gpt4 book ai didi

c++ - 如何在qsqlquerymodel(QAbstractItemModel)中编写setdata()?

转载 作者:行者123 更新时间:2023-12-03 12:50:23 28 4
gpt4 key购买 nike

我使用继承 (QSqlQueryModel) 制作了myModel,并且我 将列插入其中。我想插入 QString 类型的数据,但我不知道该怎么做。

QSQlQueryModel 是只读模型。要使其可读可写,您必须对其进行子类化并重新实现 setData()flags()

我想重写这两个方法,这是我到目前为止所做的:
dialog.cpp:

this->model = new myModel(this);
model->setQuery("SELECT * lists");
model->insertColumn(3);
model->setHeaderData(3, Qt::Horizontal, QObject::tr("string"));
qDebug() << model->setData(model->index(0,3),"string",Qt::EditRole);
// column add, column set data using setdata()
ui->tvGameList->setModel(model);

myModel.h:

class myModel : public QSqlQueryModel
{

Q_OBJECT

public:
myModel(QObject *parent = 0);
Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
bool setData(const QModelIndex &index, const QVariant &value, int role) Q_DECL_OVERRIDE;

};

myModel.cpp:

#include "mymodel.h"
#include <QSqlQuery>

myModel::myModel(QObject *parent): QSqlQueryModel(parent)
{
}

Qt::ItemFlags myModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QSqlQueryModel::flags(index);
if (index.column() == 1 || index.column() == 2)
flags |= Qt::ItemIsEditable;
return flags;
}

bool myModel::setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole)
{
if (index.isValid() && role == Qt::EditRole)
{
// I don't know here
emit dataChanged(index, index);
return true;
}
return false;
}

最佳答案

参见 Qt 示例,setData 必须像通常的 SQL 一样调用 SQL UPDATE 语句。

Qt::ItemFlags EditableSqlModel::flags(
const QModelIndex &index) const
{
Qt::ItemFlags flags = QSqlQueryModel::flags(index);
if (index.column() == 1 || index.column() == 2)
flags |= Qt::ItemIsEditable;
return flags;
}


bool EditableSqlModel::setData(const QModelIndex &index, const QVariant &value, int /* role */)
{
if (index.column() < 1 || index.column() > 2)
return false;

QModelIndex primaryKeyIndex = QSqlQueryModel::index(index.row(), 0);
int id = data(primaryKeyIndex).toInt();

clear();

bool ok;
if (index.column() == 1) {
ok = setFirstName(id, value.toString());
} else {
ok = setLastName(id, value.toString());
}
refresh();
return ok;
}

bool EditableSqlModel::setFirstName(int personId, const QString &firstName)
{
QSqlQuery query;
query.prepare("update person set firstname = ? where id = ?");
query.addBindValue(firstName);
query.addBindValue(personId);
return query.exec();
}

关于c++ - 如何在qsqlquerymodel(QAbstractItemModel)中编写setdata()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33781346/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com