QTableView:如何将鼠标hover在整个行上?

我subclassed QTableView,QAbstractTableModel和QItemDelegate。 我可以将鼠标hover在单个单元格上:

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

…但我无法弄清楚,如何hover整行。 有人可以帮助我的示例代码?

有两种方法

1)你可以使用代表来绘制行背景…
您将需要设置行在代表中突出显示,并在此基础上进行突出显示。

2)捕捉当前行的信号。 遍历该行中的项目并为每个项目设置背景。

你也可以尝试一下样式表:

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

希望它会对你们有用。

这里是我的实现,它工作得很好。首先你应该继承QTableView / QTabWidget,向mouseMoveEvent / dragMoveEvent函数中的QStyledItemDelegate发出一个信号。这个信号会发送悬停索引。

在QStyledItemDelegate中,使用成员变量hover_row_(在绑定到上面的信号的槽中更改)来告诉paint函数将哪个行悬停。

这里是代码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); } ... }