First, you subclass QTableWidget/QTableView
and reimplement mouseMoveEvent
and leaveEvent
.
In custom_table_widget.cpp
, you should have:
...
CustomTableWidget::CustomTableWidget(QWidget *parent) :
QTableWidget(parent)
{
setMouseTracking(true); // receives mouse move events even if no buttons are pressed.
}
void CustomTableWidget::mouseMoveEvent(QMouseEvent *event)
{
// detect where the mouse cursor is relative to our custom table widget
QModelIndex index = indexAt(event->pos());
emit hoverIndexChanged(index);
}
void CustomTableWidget::leaveEvent(QEvent *event)
{
// detect when the mouse cursor leaves our custom table widget
emit leaveTableEvent();
viewport()->update();
}
...
Next, you subclass QStyledItemDelegate
. Reimplement paint
method and add two slots to modify the hovered row. In row_hover_delegate.cpp
, you should have:
...
void RowHoverDelegate::onHoverIndexChanged(const QModelIndex& item) {
hovered_row_ = item.row();
}
void RowHoverDelegate::onLeaveTableEvent() {
hovered_row_ = -1;
}
void RowHoverDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const {
QStyleOptionViewItem opt = option;
if(index.row() == hovered_row_) {
opt.state |= QStyle::State_MouseOver;
} else {
opt.state &= ~QStyle::State_MouseOver;
}
QStyledItemDelegate::paint(painter, opt, index);
}
...
Finally, connect the the signals/slots and set the item delegate:
connect(my_custom_table_widget,
&CustomTableWidget::hoverIndexChanged,
my_row_hover_delegate,
&RowHoverDelegate::onHoverIndexChanged);
connect(my_custom_table_widget,
&CustomTableWidget::leaveTableEvent,
my_row_hover_delegate,
&RowHoverDelegate::onLeaveTableEvent);
my_custom_table_widget->setItemDelegate(my_row_hover_delegate);