QTableView:如何在鼠标悬停时高亮整行?

3

我对 QTableView、QAbstractTableModel 和 QItemDelegate 进行了子类化。现在我能够在鼠标悬停时悬停在单个单元格上:

void SchedulerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    ...

    if(option.showDecorationSelected &&(option.state & QStyle::State_Selected))
{
    QColor color(255,255,130,100);
    QColor colorEnd(255,255,50,150);
    QLinearGradient gradient(option.rect.topLeft(),option.rect.bottomRight());
    gradient.setColorAt(0,color);
    gradient.setColorAt(1,colorEnd);
    QBrush brush(gradient);
    painter->fillRect(option.rect,brush);
}

    ...
}

...但我不知道如何悬停整行。有人能帮我提供示例代码吗?


我正在尝试找到一种方法告诉Qt在鼠标悬停时突出显示整行,但没有成功。 - 0xbaadf00d
1
可能是QTableView如何在鼠标悬停时突出显示整行?的重复问题。 - Serafim Costa
2个回答

1

有两种方法..

1) 您可以使用委托来绘制行背景...
您需要在委托中设置行以突出显示,并基于此进行突出显示。

2) 捕捉当前行的信号。迭代该行中的项目并为每个项目设置背景。

您还可以尝试使用样式表:

QTableView::item:hover {
    background-color: #D3F1FC;
}        

希望对你们有用。

0
这是我的实现,它运行良好。首先,您应该子类化QTableView/QTabWidget,在mouseMoveEvent/dragMoveEvent函数中发出一个信号到QStyledItemDelegate。此信号将发送悬停索引。
在QStyledItemDelegate中,使用成员变量hover_row_(在绑定到上述信号的插槽中更改)告诉paint函数哪一行被悬停。
以下是代码示例:
//1: Tableview :
void TableView::mouseMoveEvent(QMouseEvent *event)
{
    QModelIndex index = indexAt(event->pos());
    emit hoverIndexChanged(index);
    ...
}
//2.connect signal and slot
    connect(this,SIGNAL(hoverIndexChanged(const QModelIndex&)),delegate_,SLOT(onHoverIndexChanged(const QModelIndex&)));

//3.onHoverIndexChanged
void TableViewDelegate::onHoverIndexChanged(const QModelIndex& index)
{
    hoverrow_ = index.row();
}

//4.in Delegate paint():
void TableViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
...
    if(index.row() == hoverrow_)
    {
        //HERE IS HOVER COLOR
        painter->fillRect(option.rect, kHoverItemBackgroundcColor);
    }
    else
    {
        painter->fillRect(option.rect, kItemBackgroundColor);
    }
...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接