c++ - 如何在 QStyledItemDelegate::paint() 中获取 QListView 的 currentIndex

标签 c++ qt

我将纯虚方法 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 (它可能是 QListViewQTableView)。

因此,一个“好方法”是将此信息保存在您的委托(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/

相关文章:

c++ - OpenGL 三角形始终为白色

c++ - 在OGDF中设置节点边界框​​大小

c++ - wglGetCurrentDC 未解析的外部

c++ - CURLOPT_WRITEFUNCTION 指向成员函数的指针

c++ - sizeof(...) = 0 或 C++ 模板中的条件变量声明

c++ - 在 C/C++ 中创建 Windows 服务的任何示例? (无图形用户界面)

c++ - 正则表达式 : C++ extract text within double quotes

Qt Installer Framework Controller 函数未被调用

c++ - 当模态窗口最小化时最小化所有应用程序窗口(在 Linux 上)

qt - 通过 QProcess 运行 .sh 脚本时出错