![](/img/trans.png)
[英]QStyledItemDelegate / QAbstractItemDelegate for QListView
[英]How to get currentIndex of QListView in QStyledItemDelegate::paint()
我將純虛方法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不是為這樣的用例設計的,因為理論上,委托不應該知道你正在使用什么視圖(它可能是QListView
或QTableView
)。
因此,“好方法”是將此信息保留在您的委托中(因為模型可能由sevaral視圖使用)。 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;
具有焦點的項目是當前項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.