我正在从使用EditStrategy OnRowChange工作的DB表中删除一行。如果我设置了OnManualSubmit,它就不能工作。我在QML端和C++函数中执行C++(),但是行没有被删除。
我继承QSqlTableModel作为MDataBaseTableModel,因为我需要在QML中显示来自SQLite DB的图像。
所以我不明白为什么removeRow()会在EditStragy::OnRowChange上工作,而不会在EditStragy::onManualSubmit上工作
以下是代码:
MDatabaseTableModel.cpp
MDataBaseTableModel::MDataBaseTableModel(QObject *parent, QSqlDatabase db,QString table):
QSqlTableModel(parent, db)
{
setEditStrategy(QSqlTableModel::OnManualSubmit);
setTable(table);
select();
}
QVariant MDataBaseTableModel::data(const QModelIndex &index, int role) const
{
QVariant value;
if (index.isValid()) {
if (role < Qt::UserRole) {
value = QSqlTableModel::data(index, role);
} else {
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlTableModel::data(modelIndex, Qt::DisplayRole);
if(roleNames().value(role) == "sqlImageData")
return QImage::fromData(value.toByteArray());
}
}
return value;
}
QHash<int, QByteArray> MDataBaseTableModel::roleNames() const
{
QHash<int, QByteArray> roles;
for (int i = 0; i < record().count(); i ++) {
roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
}
return roles;
}
bool MDataBaseTableModel::setData(const QModelIndex &item, const QVariant &value, int role)
{
if (item.isValid() && role == Qt::EditRole) {
QSqlTableModel::setData(item, value, role);
emit dataChanged(item, item);
return true;
}
return false;
}
void MDataBaseTableModel::removeRow(int row){
qDebug()<< removeRows(row, 1, QModelIndex());
select();
submitAll();
}MDataBaseTableModel.h
class MDataBaseTableModel:public QSqlTableModel
{
Q_OBJECT
public:
explicit MDataBaseTableModel(QObject * parent =0,QSqlDatabase db=QSqlDatabase(),QString, table="");
void connectDb();
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;
bool setData(const QModelIndex &item, const QVariant &value, int role = Qt::EditRole) override;
Q_INVOKABLE void removeRow(int row);
};main.cpp
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
db.setDatabaseName("products.sqlite");
db.open()
MDataBaseTableModel* categoryModel = new MDataBaseTableModel(0,db,"categoryTable");
engine.rootContext()->setContextProperty("categorySQL", categoryModel);main.qml
ListView {
id: listView
implicitWidth: window.width /5
implicitHeight: window.height/4
model : categorySQL
delegate: ItemDelegate{
width: parent.width
MouseArea {
anchors.fill: parent
onClicked: {
listView.currentIndex = index
}
}
Text{
text : sqlName
}
}
}
Button {
text: "-"
onClicked: {
categorySQL.removeRow(listView.currentIndex)
categorySQL.submitAll()
}
}发布于 2020-10-13 15:35:07
probem在submitAll()之前是select();
void MDataBaseTableModel::removeRow(int row){
qDebug()<< removeRows(row, 1, QModelIndex());
select();
submitAll();
}https://stackoverflow.com/questions/64320850
复制相似问题