从一行移动到另一行时,工具提示不会更新

Tooltip is not updated on moving from one row to another

我已经对 QAbstractTableModel 进行了子类化,并且在 data() 函数中,我在每行的最后一列中显示了一个图像,并在鼠标悬停时显示了一个工具提示。

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();
}

工具提示文本在每一行上显示正常,但是当我将光标从一行的最后一列移动到它正下方的另一最后一列(或其下方的任何行)时,工具提示仍保留在上一行。

如果在移动到另一行的最后一列之前将光标移动到任何其他单元格,则此问题不会持续存在。 感谢您的帮助。

如果显示为工具提示的数据对于视图中的不同项目是相同的,则不会调整工具提示的位置。不确定这是设计特性还是错误 - 需要查看 Qt 源代码。

不过你可以很容易地解决这个问题。在 Qt 文档中,您可以找到此类信息:

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.

因此,子类化您的视图并覆盖 viewportEvent 方法应该可以解决您的问题。