Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to highlight the entire row on mouse hover in QTableWidget: Qt5

I want to highlight the row on mouse hover in my QTableWidget.

When I hover the mouse, only single cell highlighted.

I have tried this approach :

bool MyTabWidget::eventFilter(QObject *target, QEvent *event)
{
    if( target == ui->MyTableWidget )
    {
        //Just to print the event type
        qDebug() <<"EventType : "<<event->type();
    }
}

Output : EventType : 13.

`(13 = QEvent::Move)`

I have done lost of googling. but not get any proper solution.

Is there any other approach to fulfill my requirment (to highlight entire row on mouse hover)?

Please help. Thank in advance.

EDIT:

Please refer below screen shot for more clear.

enter image description here

This is my QTableWidget I want to change the background color of that red boarder(edited) row on mouse hover.

like image 766
AB Bolim Avatar asked Apr 16 '14 13:04

AB Bolim


2 Answers

Here is my implementation,it works well.First you should subclass QTableView/QTabWidget ,emit a signal to QStyledItemDelegate in mouseMoveEvent/dragMoveEvent function .This signal will send the hovering index.

In QStyledItemDelegate ,use a member variable hover_row_(changed in a slot bind to above signal) to tell paint function which row is be hovered.

Here is the code examaple:

//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);
    }
...
}
like image 71
baixiangcpp Avatar answered Sep 21 '22 13:09

baixiangcpp


I had similar task and answer from baixiangcpp helped me, but it worked only when mouse button was pressed, not on simple hovering. I resolved this issue with help from user mrjj on qt forum, who suggested I should set "mouseTracking" property in TableView (CustomView in my case) to "true".

CustomView::CustomView(QWidget *parent) : QTableView(parent)
{
    this->setMouseTracking(true);
    connect(this,SIGNAL(hoverIndexChanged(const QModelIndex&)),parent,SLOT(onHoverIndexChanged(const QModelIndex&)));
  }
like image 38
max paint Avatar answered Sep 19 '22 13:09

max paint