如何在QStyledItemDelegate::paint()中获取QListView的currentIndex
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
)。
所以,一个"好方法"是将这些信息保存在代理中(因为模型可能被多个视图使用)。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;
具有焦点的项目是当前项目。
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 如何防止QListView在启动时获取所有图标?
- 如何从QListView中获取所选项目
- 如何在QStyledItemDelegate::paint()中获取QListView的currentIndex