【问题标题】:QTableView: how to hover an entire row on mouse over?QTableView:如何将鼠标悬停在整行上?
【发布时间】:2013-01-09 19:56:09
【问题描述】:

我对 QTableView、QAbstractTableModel 和 QItemDelegate 进行了子类化。我可以将鼠标悬停在单个单元格上:

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

    ...
}

...但我不知道如何悬停整行。有人可以帮我提供示例代码吗?

【问题讨论】:

标签: windows qt hover row qtableview


【解决方案1】:

有两种方法..

1) 您可以使用委托来绘制行背景...
您需要将行设置为在委托中突出显示,并基于此, 做高亮显示。

2) 捕捉当前行的信号。迭代该行中的项目 和 为每个项目设置背景。

你也可以试试样式表:

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

希望对你们有用。

【讨论】:

    【解决方案2】:

    这是我的实现,效果很好。首先你应该继承 QTableView/QTabWidget ,在 mouseMoveEvent/dragMoveEvent 函数中向 QStyledItemDelegate 发出一个信号。这个信号将发送悬停索引。

    在 QStyledItemDelegate 中,使用成员变量 hover_row_(在插槽中更改为绑定到上述信号)告诉绘制函数哪一行被悬停。

    代码示例如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 2020-01-03
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多