using a QRubberBand on top of a QGraphicsItem
I am trying to make it so that if a user clicks on a QGraphicsItem it will make a QRubberBand for just that item.
I have the following in my class:
void ImagePixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event){
if(currentKey == Qt::Key_Control){
qDebug("This is a control click");
origin = event->screenPos();
if (!selected.isNull())
selected = new QRubberBand(QRubberBand::Rectangle, event->widget());
selected->setGeometry(QRect(origin, QSize()));
selected->show();
}
}
This is giving me an error on the setGeometry call, but no additional information. This was essentially code I got f开发者_StackOverflowrom QRubberBand, except that I had to use event.screePos() and I had to set the constructor of QRubberBand to event.widget() instead of "this" because, I think, QGraphicsItem does not inherit from QWidget?
Is there a better way of doing this?
Thanks
I made this example, I hope to help
My custom item.
#ifndef ITEM_H
#define ITEM_H
#include <QtCore>
#include <QtGui>
class Item : public QGraphicsRectItem
{
public:
Item()
{
setRect(0,0,100,100);
}
void mousePressEvent(QGraphicsSceneMouseEvent * event)
{
origin = event->screenPos();
if (!rubberBand)
rubberBand = new QRubberBand(QRubberBand::Rectangle,0);
rubberBand->setGeometry(QRect(origin, QSize()));
rubberBand->show();
}
void mouseMoveEvent(QGraphicsSceneMouseEvent * event )
{
QRectF inside = QGraphicsRectItem::boundingRect();
QPointF mapPoint = mapFromScene(event->pos());
if(inside.contains(mapPoint))
rubberBand->setGeometry(QRect(origin, event->screenPos()).normalized());
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent * event )
{
rubberBand->hide();
}
private:
QRubberBand * rubberBand;
QPoint origin;
};
#endif // ITEM_H
and show the view
#include <QtGui>
#include "item.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView w;
QGraphicsScene s;
Item * item = new Item();
w.setScene(&s);
s.addItem(item);
w.show();
return a.exec();
}
精彩评论