模拟鼠标悬停在 QTreeView 的项目上

Simulate mouse hover on an item of QTreeView

在 Qt 包中,是否可以通过编程方式实现 QTreeView 中某个项目的突出显示(如鼠标悬停时所见)?

我可以 select 该项目并且它给人以类似的印象,但我不能使用这种方法(因为我在其他地方使用 selections)。

最后一个选项是在项目本身中存储一个标志,并 return 背景或来自 data() 方法的某种角色的字体。但是这种方法看起来很繁琐。

我最终听从了 vahancho 的建议。

在我的模型中,我在 data(QModelIndex index) 方法中添加了以下内容:

if (role == Qt::BackgroundColorRole)
{
    if (HasHighlighted && (index == LastHighlightedIndex))
    {
        return qVariantFromValue(QColor(229, 243, 255)); //highlighting color, at least on Windows10
    }
}

为了突出我打电话

void TreeModel::SetHighlighted(QModelIndex & index)
{
    if (index != LastHighlightedIndex || !HasHighlighted)
    {
        if (HasHighlighted)
        {
            emit dataChanged(LastHighlightedIndex, LastHighlightedIndex); //clearing previous highlighted 
        }
        LastHighlightedIndex = index;
        HasHighlighted = true;
        emit dataChanged(index, index);
    }

}

在我的例子中,我使用代理,所以我需要获得正确的索引:使用 GetModelIndex 方法

void CustomTreeView::SimulateHover(QModelIndex index)
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->SetHighlighted(proxy->GetModelIndex(index));
    }
}

-

QModelIndex TreeProxyModel::GetModelIndex(QModelIndex & index)
    {
        return mapToSource(index);
    }

除了清除上次悬停:

void CustomTreeView::ClearSimulatedHover()
{
    TreeProxyModel *proxy = dynamic_cast<TreeProxyModel*>(this->model());
    if (proxy != nullptr)
    {
        proxy->model()->ClearHighlighted();
    }
}