2013-01-09 40 views
3

我分類了QTableView,QAbstractTableModel和QItemDelegate。我可以懸停在鼠標上的單個單元格:QTableView:如何將鼠標懸停在整行上?

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

    ... 
} 

...但我弄不明白,如何懸停整行。有人可以幫助我瞭解示例代碼嗎?

+0

我試圖找到一種方式來告訴Qt來突出鼠標懸停時,沒有運氣整行.. – 0xbaadf00d

+1

的[QTableView中可能重複我怎麼能突出鼠標懸停的整個行?](https://stackoverflow.com/questions/20565930/qtableview-how-can-i-highlight-the-entire-row-for-mouse-hover) –

回答

1

有2種方式..

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

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

你也可以嘗試樣式表:

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

希望,這將有用到你們。

0

這裏是我的實現,它工作的很好。首先你應該繼承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); 
    } 
... 
}