QSqlTableModel delegate is not updated after DELET

2019-09-14 06:41发布

I have the following class

class SqlContactModel : public QSqlTableModel
{
    Q_OBJECT
public:
    SqlContactModel(QObject *parent = 0);
    Q_INVOKABLE void addContact( const QString& contactName );
    Q_INVOKABLE void removeContact( const QString& contactName );

    QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
    QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;
};

used as a model for ListView. I have the following implementation for add/remove methods :

void SqlContactModel::addContact( const QString& contactName )
{
    QSqlRecord newRecord = record();
    newRecord.setValue("name", contactName);
    if (!insertRecord(rowCount(), newRecord)) {
        qWarning() << "Failed to send message:" << lastError().text();
        return;
    }

    submitAll();
}

void SqlContactModel::removeContact( const QString& contactName )
{
    QString sqlQueryString = QString("DELETE FROM Contacts WHERE name='") + contactName + QString("'");
    QSqlQuery query;
    if (!query.exec(sqlQueryString))
        qFatal(qPrintable(query.lastError().text()));
    submitAll();
}

And finally inside qml I'm trying to call the following sequence :

Component.onCompleted: {
   addContact("111");
   addContact("123")
   addContact("456")
   removeContactFromModel("456");
   console.log("contactsList.count = ", contactsList.count)
 }

but I see that 3 delegates are still inside ListView. At the same time I see that there are only 2 entries inside my database. What is wrong in this approach? How to get ListView updated each time I add/remove items in my DB?

The latest finding is that this issue happens if for some reason contacts "111" and "123" are already in DB before calling this onComplete. Any ideas?

1条回答
Rolldiameter
2楼-- · 2019-09-14 07:06

You are not using the specific methods of the class to remove the rows, try to use:

bool removeRow(int row, const QModelIndex &parent = QModelIndex())

This method implements the removing protocol of QT model classes.

Another solution emitting signals:

emit beginRemoveRows(const QModelIndex &parent, int first, int last);
YOUR CODE
emit endRemoveRows();

Or

emit beginResetModel();
YOURCODE
emit endResetModel();

Hope this help you.

查看更多
登录 后发表回答