2017-05-24 257 views
2

我想覆盖函数drawBranches() in QTreeView
我分类了QTreeView类,然后我复制drawBranches()函数从here。在这个函数改变任何事情之前,我希望确保它工作第一,但构建失败,出现此错误:Qt - 覆盖QTreeView :: drawBranches()

error: 'const QTreeViewPrivate* QTreeView::d_func() const' is private 
inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr)); } \ 

这里是我的代码:

class MyTreeView : public QTreeView 
{ 
    Q_OBJECT 
public: 
    MyTreeView(QWidget *parent =0) : QTreeView(parent) {} 
    void drawBranches(QPainter * painter, const QRect &rect, const 
         QModelIndex &index)const 
    { 
     Q_D(const QTreeView); 
     const bool reverse = isRightToLeft(); 
     const int indent = d->indent; 
     const int outer = d->rootDecoration ? 0 : 1; 
     const int item = d->current; 
     const QTreeViewItem &viewItem = d->viewItems.at(item); 
     int level = viewItem.level; 
     QRect primitive(reverse ? rect.left() : rect.right() + 1, rect.top(), indent, rect.height()); 

     ....// Moore lines that I copied 

      else 
       opt.state &= ~QStyle::State_MouseOver; 
      style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt, painter, this); 
      current = ancestor; 
      ancestor = current.parent(); 
     } 
     painter->setBrushOrigin(oldBO); 
} 

};

有许多行,其中d指针被使用并且它是私有的,e.g d->indent;

如何在不违反私人角色的情况下获得对此指针的引用?

为什么我要重写这个功能:我想隐藏的,除了那些谁拥有水平(高级别)的所有项目的展开/折叠指标,我想通过重写这个功能,我可以做到这一点。

感谢

回答

1

您需要咨询reference on using Qt PIMPL idiom

每个d_func是私有的。你需要申报你自己的。你的是一个特例,因为你不是从QTreeViewPrivate派生的,因此返回的类型仍然是QTreeViewPrivate*。 Qt提供了一个方便的宏做的工作适合你:不是从随机库复制代码

// Interface 
#include <QTreeView> 

class MyTreeView : public QTreeView 
{ 
    Q_OBJECT 
    Q_DECLARE_PRIVATE(QTreeView) 
public: 
    MyTreeView(QWidget * parent = {}) : QTreeView{parent} {} 
protected: 
    void drawBranches(QPainter *, const QRect &, const QModelIndex&) const override; 
}; 
// Implementation 
#include <private/qtreeview_p.h> 

void MyTreeView::drawBranches(QPainter * painter, const QRect &rect, const 
           QModelIndex &index)const 
{ 
    Q_D(const QTreeView); 
    ... 
} 

此外,你应该把它复制from the official mirror

+0

感谢回复和感谢提示:''从官方镜像'。我有一个问题与QT + = gui-private拒绝包含,但我想我可以解决它。 – Phiber

+0

添加QT + =小部件 - 私人而不是gui-private让它起作用 – Phiber