The selection behavior is set to select rows, but only the hovered cell is highlighted. Is there any way to highlight the entire row?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There are 2 ways..
1) You can use delegates to draw the row background...
You will need to set the row to highlight in the delegate and based on that, do the highlighting.2) Catch the signal of current row. Iterate over the items in that row and set background for each item.
Hope, It will usefull to you guys.
回答2:
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);