Tooltip is not updated on moving from one row to a

2019-09-15 15:41发布

问题:

I have subclassed QAbstractTableModel and in data() function I am displaying an image in last column of each row and a tooltip on mouse hover.

QVariant MyTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
    return QVariant();

if (role == Qt::DisplayRole)
{
    switch (index.column())
    {
     // few cases
    default:
        return QVariant();
    }
}
else if (role == Qt::CheckStateRole && index.column() == 0)
{
    int state= tableData.at(index.row()).state;
    if (state)
        return Qt::Checked;
    else
        return Qt::Unchecked;
}
else if (role == Qt::DecorationRole && index.column() == 7 && index.row() > 1)
{
    QPixmap pixMap(fileName);
    return pixMap;
}
else if (role == Qt::ToolTipRole && index.column() == 7 && index.row() > 1)
{
    return QString("Delete");
}
else
    return QVariant();
}

Tooltip text is displayed fine on each row but when I move cursor from last column of a row to another last column just below it(or any row below it) tooltip remains on the upper row.

This issue does not persist if cursor is moved to any other cell before moving to last column of another row. Thanks for help.

回答1:

When data displayed as a tooltip is the same for different items in the view the tooltip position isn't adjusted. Not sure if this is a design feature or bug - would need to look into Qt sources.

You can fix that quite easily though. In Qt documentation you can find such information:

Note that, if you want to show tooltips in an item view, the model/view architecture provides functionality to set an item's tool tip; e.g., the QTableWidgetItem::setToolTip() function. However, if you want to provide custom tool tips in an item view, you must intercept the help event in the QAbstractItemView::viewportEvent() function and handle it yourself.

Hence, subclassing your view and overriding the viewportEvent method should solve your problem.