首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在QStyledItemDelegate::QListView ()中获取QListView

如何在QStyledItemDelegate::QListView ()中获取QListView
EN

Stack Overflow用户
提问于 2016-07-27 12:05:30
回答 3查看 1.3K关注 0票数 4

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

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

但我不知道如何知道绘图项当前或无(与来自QListView::currentIndex()的相同项)。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-07-27 13:23:43

Qt MVC不是为这样的用途而设计的,因为理论上,委托不应该知道您使用的是什么视图(可能是QListViewQTableView)。

因此,“好方法”是将此信息保存在委托中(因为模型可能由sevaral视图使用)。Fox示例(伪代码):

代码语言:javascript
复制
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
    }

}
票数 1
EN

Stack Overflow用户

发布于 2017-08-21 10:55:15

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

代码语言:javascript
复制
void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
    bool selected = index == parent()->currentIndex();
}
票数 1
EN

Stack Overflow用户

发布于 2016-07-27 12:49:49

你走在正确的轨道上:

代码语言:javascript
复制
auto current = option.state & QStyle::State_HasFocus;

具有焦点的项是当前项。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38612462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档