如何在QStyledItemDelegate::paint()中获取QListView的currentIndex

How to get currentIndex of QListView in QStyledItemDelegate::paint()

本文关键字:获取 QListView currentIndex QStyledItemDelegate paint      更新时间:2023-10-16

我将纯虚拟方法QStyledItemDelegate::paint定义为:

void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    bool selected = option.state & QStyle::State_Selected;
    // ...
    // drawing code
}

但我不知道如何知道绘图项目是当前的还是否(与QListView::currentIndex()中的项目相同)。

Qt-MVC不是为此类用例设计的,因为从理论上讲,委托不应该知道您使用的是什么视图(可能是QListViewQTableView)。

所以,一个"好方法"是将这些信息保存在代理中(因为模型可能被多个视图使用)。Fox示例(伪代码):

class FooViewDelegate : ...
{
private:
  QModelIndex _currentIndex;
  void connectToView( QAbstractItemView *view )
  {
    connect( view, &QAbstractItemView::currentChanged, this, &FooViewDelegate ::onCurrentChanged );
  }
  void onCurrentChanged( const QModelIndex& current, const QModelIndex& prev )
  {
    _currentIndex = current;
  }
public:
    void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
    {
        bool selected = index == _currentIndex;
        // ...
        // drawing code
    }
}

委托的父级是视图,您可以直接从视图中获取当前索引。

void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    bool selected = index == parent()->currentIndex();
}

您正沿着正确的轨道前进:

auto current = option.state & QStyle::State_HasFocus;

具有焦点的项目是当前项目。