Reputation: 255
I defined pure virtual method QStyledItemDelegate::paint
as:
void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
bool selected = option.state & QStyle::State_Selected;
// ...
// drawing code
}
But I cant't figure how to know is the drawing item current or no (The same item as from QListView::currentIndex()
).
Upvotes: 4
Views: 1675
Reputation: 1598
The parent of the delegate is the view, you can directly obtain the current index from the view.
void FooViewDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
bool selected = index == parent()->currentIndex();
}
Upvotes: 1
Reputation: 8994
Qt MVC is not designed for such usecases, because, theoretically, delegate should not know, what view you are using (it may be QListView
or QTableView
).
So, a "good way" is to keep this information inside your delegate (because model may be used by sevaral views). Fox example (pseudo-code):
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
}
}
Upvotes: 1
Reputation: 98445
You're along the right track:
auto current = option.state & QStyle::State_HasFocus;
The item with focus is the current item.
Upvotes: 0