QTableView How can I select an entire row for mouseover?

The selection behavior is set to select rows, but only the hovering cell is highlighted. Is there a way to highlight the entire line?

0
source share
2 answers

There are two ways.

1) You can use delegates to draw the background of the string ... You will need to set the string to highlight in the delegate and based on this, make a selection.

2) Catch the signal of the current line. Iterate the elements in this line and also set the background for each element.

Hope this will be helpful for you guys.

+1
source

QTableWidget/QTableView mouseMoveEvent leaveEvent.

custom_table_widget.cpp :

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

QStyledItemDelegate. Reimplement paint , . row_hover_delegate.cpp :

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

, / :

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

All Articles