2

在我的应用程序中,我有两种对象类型。一个是字段项,另一个是复合项。复合项目可能包含两个或多个字段项目。这是我的复合项目实现。

#include "compositeitem.h"

CompositeItem::CompositeItem(QString id,QList<FieldItem *> _children)
{
   children = _children;
}

CompositeItem::~CompositeItem()
{
}

QRectF CompositeItem::boundingRect() const
{
 FieldItem *child;
     QRectF rect(0,0,0,0);
     foreach(child,children)
     {
        rect = rect.united(child->boundingRect());
     }
    return rect;
}

void CompositeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,   QWidget *widget )
  {
   FieldItem *child;
   foreach(child,children)
   {
      child->paint(painter,option,widget);
   }
  }

  QSizeF CompositeItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
  {
   QSizeF itsSize(0,0);
   FieldItem *child;
   foreach(child,children)
   {
      // if its size empty set first child size to itsSize
      if(itsSize.isEmpty())
          itsSize = child->sizeHint(Qt::PreferredSize);
      else
      {
          QSizeF childSize = child->sizeHint(Qt::PreferredSize);
              if(itsSize.width() < childSize.width())
                  itsSize.setWidth(childSize.width());
              itsSize.setHeight(itsSize.height() + childSize.height());
      }
  }
  return itsSize;
     }

     void CompositeItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
     {
          qDebug()<<"Test";
     }

我的第一个问题是如何将上下文菜单事件传播给特定的孩子。

复合材料1

上面的图片展示了我可能的复合项目之一。

如果您查看上面的代码,您会看到我在上下文菜单事件发生时打印“测试”。

当我右键单击行符号时,我看到打印了“测试”消息。但是当我右键单击信号符号“测试”时没有打印,我希望它被打印。

我的第二个问题是什么导致了这种行为。我该如何克服这一点。

4

2 回答 2

0

您可以尝试使用 mouseRelease 事件重新实现您的 contextMenu 吗?

void CompositeItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
        if(event->button() == Qt::RightButton)
        {
            contextMenu->popup(QCursor::pos());
        }
}
于 2010-05-11T21:51:08.683 回答
0

我发现捕捉事件可能有两种解决方案。第一个是重新实现形状函数。就我而言,它将像这样实现。

QPainterPath shape() const
{
  QPainterPath path;
  path.addRect(boundingRect());
  return path;
}

第二个是使用QGraphicsItemGroup如果您直接将项目添加到场景中,使用QGraphicsItemGroup
将是个好主意。但在我的情况下,我必须继承 QGraphicsItemGroup因为我使用的是布局。所以暂时我选择写我自己的项目。

于 2010-05-13T07:20:51.817 回答