QTableView: how to hover an entire row on mouse over?

我们两清 提交于 2019-12-12 15:40:01

问题


I subclassed QTableView, QAbstractTableModel, and QItemDelegate. I am able to hover a single cell on mouse over:

void SchedulerDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    ...

    if(option.showDecorationSelected &&(option.state & QStyle::State_Selected))
{
    QColor color(255,255,130,100);
    QColor colorEnd(255,255,50,150);
    QLinearGradient gradient(option.rect.topLeft(),option.rect.bottomRight());
    gradient.setColorAt(0,color);
    gradient.setColorAt(1,colorEnd);
    QBrush brush(gradient);
    painter->fillRect(option.rect,brush);
}

    ...
}

... but I cannot figure out, how to hover an entire row. Can Someone help me with sample codes?


回答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.

you can also tried style sheet:

QTableView::item:hover {
    background-color: #D3F1FC;
}        

Hope, It will usefull to you guys.




回答2:


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


来源:https://stackoverflow.com/questions/14245365/qtableview-how-to-hover-an-entire-row-on-mouse-over

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