如何在QStyledItemDelegate::paint()中获取QListView的当前索引(currentIndex)

4

我将纯虚函数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()中的相同项)。

3个回答

1
代理的父视图是View,您可以直接从View中获取当前索引。
void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    bool selected = index == parent()->currentIndex();
}

1

Qt MVC 不适用于这种用例,因为理论上委托应该不知道您使用的是哪个视图(可能是 QListViewQTableView)。

因此,“好的方法”是将此信息保存在您的委托中(因为模型可能被多个视图使用)。例如(伪代码):

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
    }

}

明白这个概念。顺便问一下,在QListView上默认是如何工作的?他们是使用同样的技巧吗? - Vladimir Gamalyan
也许我不知道。但是 QListWidget 封装了自己的模型。你可以查看 Qt 代码以找到确切的答案。 - Dmitry Sazonov
1
你应该从答案中删除旧的想法。Stack Overflow会跟踪你的编辑历史,整个“EDIT:...”“惯例”真的很愚蠢。如果有人对你的编辑历史感兴趣,他们可以使用修订跟踪系统来查看。 - Kuba hasn't forgotten Monica
请注意,protected:QAbstractItemView::currentChanged 无法从 FooViewDelegate 访问。但这不是问题,有许多不同的方法可以将更改传递给 FooViewDelegate。谢谢! - Vladimir Gamalyan
@VladimirGamalian 您是正确的。可能应该通过选择模型来完成它。 - Dmitry Sazonov

0

你走在正确的轨道上:

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

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


我已经尝试过这个,但它只能在我们切换到另一个小部件后才能正常工作。 - Vladimir Gamalyan
@VladimirGamalian 请尝试使用 QStyle::State_Active。如果这不起作用,并且我们仍然假设 option.state 具有所需的数据,请以十六进制转储它并查看哪个位表示当前项目:qDebug() << QString::number((uint)option.state, 16); - Kuba hasn't forgotten Monica
好主意,但不幸的是,在焦点移动到另一个小部件后,只有“1”、“1”、“1”、“1”、“1”。 - Vladimir Gamalyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接