Sturm
Sturm

Reputation: 4125

Simulate mouse hover on an item of QTreeView

In Qt package, is it possible to achieve highlighting (as seen when hovering with the mouse) of an item in QTreeView programmatically?

I am able to select the item and it gives a similar impression, but I cannot use this method (since I am using selections in some other place).

The last option would be to store a flag in the item itself and return a background or a font from data() method for some role. But this approach seems very tedious.

enter image description here

Upvotes: 0

Views: 626

Answers (1)

Sturm
Sturm

Reputation: 4125

I ended up following vahancho advice.

In my model I have added the following in the data(QModelIndex index) method:

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

To highlight I call

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

}

In my case I use a proxy so I need to get the right index: with the GetModelIndex method

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

In addition to clear last hover:

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

Upvotes: 2

Related Questions