我将纯虚方法 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不是为此类用例设计的,因为从理论上讲,委托(delegate)不应该知道您正在使用什么 View (它可能是 QListView
或 QTableView
)。
因此,一个“好方法”是将此信息保存在您的委托(delegate)中(因为模型可能会被多个 View 使用)。 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
}
}
关于c++ - 如何在 QStyledItemDelegate::paint() 中获取 QListView 的 currentIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38612462/