Context menu on QGraphicsWidget
In my application, I have two types of object. One is a field element, the other is a compound element. Composite elements can contain two or more field elements. Here is my composite element implementation.
#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";
}
My first question is how to pass a context menu event to a specific child element?
The image above shows one of my possible building blocks.
If you look at the code above, you can see that I am typing "Test" when the context menu event occurs.
When I right-click on the line symbol, I see that the message "Test" is printed. But when I right click on the signal, the Test symbol is not printed and I want it to be printed.
My second question is what caused this behavior. How can I overcome this.
a source to share
I realized that there could be two solutions for catching events. First, overriding the shape . In my case, it will be implemented as follows.
QPainterPath shape() const
{
QPainterPath path;
path.addRect(boundingRect());
return path;
}
Second is to use QGraphicsItemGroup
It is a good idea to use QGraphicsItemGroup if you are just adding your items to the scene. But in my case I have to subclass QGraphicsItemGroup due to the fact that I am using layout. So temporarily I am writing my own element.
a source to share
