Changing of C++ model doesn't update QML ListView
-
Hi. During the process of moving from QWidgets to QML I faced with the next problem: changing of C++ model doesn't update QML ListView. But on QWidgets all works as expected, i.e: emitting of
dataChanged(index(0), index(rowCount()))
signal updates my QListView from QWidgets.My C++ model gets data through "Dispatcher" class, which returns different count of elements and values for roles for different ID, for example:
rowCount(...)
method of my model looks like this:int ChatModel::rowCount( const QModelIndex &theIndex ) const { return _ChatDispatcher->messageCount(); }
And here is
messageCount()
method of my Dispatcher:_DialogID
- field of Dispatcher classint ChatDispatcher::messageCount() { return GetMessagesCount( _DialogID ); }
And when i change
_DialogID
i want to redraw the ListView by emittingdataChanged(index(0), index(rowCount()))
signal. But for QML ListView it doesn't work.I've tryed this instead of
dataChanged(..)
:beginResetModel(); endResetModel();
It works, but very slowly. Maybe you advise me something useful?
-
Maybe this helps: if the number of rows changes, you have to call also QAbstractModel::beginInsertRows() and endInsertRows() - these take care of emitting the signals like rowsAboutToBeInserted() etc. - and these seem to be important for QML view updates.
-
I call it by click on Qml button:
RoundedButton { id: sendButton; text: "send"; anchors { right: parent.right; bottom: parent.bottom; rightMargin: dp(15); bottomMargin: dp(15); } onClicked: sendMessage(); } function sendMessage() { if( messageInput.text !== "" ){ chatDispatcher.addMessage( messageInput.text ); messageInput.text = ""; chatModel.updateMessageView(); } }
And i've tryed to emit dataChanged() signal like that:
void ChatModel::updateMessageView() { dataChanged( index( 0 ), index( rowCount() ) ); }
-
@p3c0
My model gets all data from database through my "Dispatcher" class as i described above.See:
int ChatModel::rowCount( const QModelIndex &theIndex ) const { return _ChatDispatcher->messageCount(); }
And
addMessage
method inserts data to database. After that i want to redraw my listview -
The
dataChanged
signal of models in QML should also say which roles are changed. The 3rd param is missing. -
When no roles are passed as a parameter, all roles ares assumed to be changed.
The most likely error of OP is to not call begin/endInsertRows (or modelReset is all the model is changed)