Search code examples
c++qtqt5qt4qabstractitemmodel

In QAbstractItemModel::data() const, how can i add some thread safe data


In QAbstractItemModel::data(), how can i add some thread safe data

QAbstractItemModel::data() is a 'const' function, so I cannot add my scope mutex lock, but my data must be changed in somewhere, so it must be need a mutex lock, how can I solve this issue?

ps: I have tried connect/emit, but the signal also need 'const' keyword, so do i need use TCP socket??

QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
{
    QMutexLocker locker(&cacheMutex_);
    auto cacheTime = logCache_.find(key_);
}

Solution

  • From your code snippet I believe you mean to add some synchronization object as derived class member. If so @Tas' comment is already an answer: synchronization objects are not conceptually considered part of your data, so just mark them mutable in your derived class:

    mutable QMutex cacheMutex_;

    Data member marked mutable can still be modified in a const member function.