Search code examples
qtsignals-slots

Sorting a model has no immediate effect


I implemented sort in a QAbstractTableModel subclass. The sorting itself works but the view doesn't change until I hover over the table itself (i.e. not the header). How can I fix this? At first I thought that I also have to emit a signal but couldn't find an appropriate one.


Solution

  • I use the following code to sort my model in a project:

    void MyModel::organize()
    {
        if (!cache_ || cache_->empty()) return;
        beginResetModel(); // (a)
        std::stable_sort(cache_->begin(), cache_->end(), compareRow);
        endResetModel(); // (b)
    } // end:(MyModel::organize)
    

    line (a) tells the model that I'm going to re-organize data, line (b) tells the model that I'm finished, please refresh the associated views.

    You may also emit dataChanged(index, index); signal.