QTableView How can I highlight the entire row for mouse hover?

微笑、不失礼 提交于 2019-12-11 19:32:19

问题


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


来源:https://stackoverflow.com/questions/20565930/qtableview-how-can-i-highlight-the-entire-row-for-mouse-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!