Search code examples
c++qtmodelmodel-view

Broken selection in a custom QAbstractItemModel and QTableView


I'm working on a QTableView control with lazy loading.

I have thousands of records it has to display and it used to lag badly when I used a simple QListWidget approach.

Now I use QAbstractItemModel with the following data method:

QVariant MyModel::data(const QModelIndex & index, int role) const
{
    int col = index.column();
    int row = index.row();

    if (role == Qt::DecorationRole && col == 0)
    {            
        return getIcon(row); // icons in the first column
    }
    else if (role == Qt::DisplayRole && col == 1)
    {
        return getText(row); // text in the second column            
    }
    else
    {
        return QVariant();
    }
}

The resulting table view works great: it is fast and smooth.

There's one major problem though: the selection is completely broken.

When I select an item/items, they are not highlighted in blue right away, I need to scroll the table so that it repaints and shows blue background. (I'm using Windows 7.)

Also I don't see the dotted rectangle when selecting items.

I checked, the selection model of the table view is not null. Also I looked at some other model implementations in Qt, they have similar data method, but there's no selection problems with them.

I also tried subclassing from QAbstractTableItem and QAbstractListItem, nothing.

Appreciate your help here.


Solution

  • Sorry about this silly question...

    I solved this by removing the following line:

    tableView->setRootIndex(model->index(0, 0));