2013-12-13 120 views

回答

1

有2種方式..

1)您可以使用委託繪製行背景...
您將需要設置該行的委託,以突出和此基礎上, 突出顯示。

2)抓住當前行的信號。迭代該行中的項目 和 爲每個項目設置背景。

希望它會對你們有用。

+0

.Could請您給一些關於第一種方法 – IMAN4K

1

首先,您的子類QTableWidget/QTableView和重新實現mouseMoveEventleaveEvent

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

謝謝你的代碼解釋,但並不是真的有必要。 – 0xbaadf00d

相關問題