//////RectItem.h
#include <QGraphicsRectItem>
#include <QGraphicsSceneContextMenuEvent>
#include <QStyleOptionGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>
#include <QWidget>
#include <QMenu>
{
public:
~RectItem();
};
/////////////its corresponding cpp file
#include "RectItem.h"
{
menu.addAction("Menu");
}
RectItem::~RectItem()
{}
QRectF RectItem
::boundingRect() const {
}
{
}
{
menu.exec(event->screenPos());
}
//////RectItem.h
#include <QGraphicsRectItem>
#include <QGraphicsSceneContextMenuEvent>
#include <QStyleOptionGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>
#include <QWidget>
#include <QMenu>
class RectItem: public QGraphicsRectItem
{
public:
RectItem(QRectF, QGraphicsItem* parent = 0, QGraphicsScene* scene = 0 );
~RectItem();
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void contextMenuEvent(QGraphicsSceneContextMenuEvent *);
QMenu menu;
};
/////////////its corresponding cpp file
#include "RectItem.h"
RectItem::RectItem(QRectF rect, QGraphicsItem* parent , QGraphicsScene* scene ):
QGraphicsRectItem(rect, parent, scene)
{
menu.addAction("Menu");
}
RectItem::~RectItem()
{}
QRectF RectItem::boundingRect() const
{
return QGraphicsRectItem::boundingRect();
}
void RectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QGraphicsRectItem::paint(painter, option, widget);
}
void RectItem::contextMenuEvent(QGraphicsSceneContextMenuEvent * event)
{
menu.exec(event->screenPos());
}
To copy to clipboard, switch view to plain text mode
Now, the latter code resides in a class, which holds a qgraphicsview in its ui:
RectItem
* item
=new RectItem
(QRectF(0,
0,
50,
50));
scene->addItem(item);
item->setPos(0,0);
item->setZValue(1);
item->show();
ui.graphicsView->setScene(scene);
ui.
graphicsView->setSceneRect
(QRectF(-100,
-100,
200,
200));
ui.graphicsView->scale(0.2,0.2);
QGraphicsScene *scene=new QGraphicsScene();
RectItem * item=new RectItem(QRectF(0,0,50,50));
scene->addItem(item);
item->setPos(0,0);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIgnoresTransformations, true);
item->setZValue(1);
item->show();
ui.graphicsView->setScene(scene);
ui.graphicsView->setSceneRect(QRectF(-100,-100,200,200));
ui.graphicsView->scale(0.2,0.2);
To copy to clipboard, switch view to plain text mode
The context menu works only in a smaller space of the rectangle. The selectable area is not the rectangle seen on the screen.
Thanks in advance
Bookmarks