选择行为设置为选择行,但仅突出显示悬停的单元格。有没有办法突出整行?
答案 0 :(得分:3)
首先,您继承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
。重新实现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 :(得分:1)
有两种方式..
1)您可以使用委托来绘制行背景...
您需要在委托中设置要突出显示的行,并根据该行, 突出显示。2)抓住当前行的信号。迭代该行中的项目 和 为每个项目设置背景。
希望,这对你们有用。