在QGraphicsItem上使用QRubberBand
问题描述:
我正在试图让用户点击一个QGraphicsItem,它会为该项目创建一个QRubberBand。在QGraphicsItem上使用QRubberBand
我在我的类中的下列:
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();
}
}
这是给我的setGeometry调用一个错误,但没有额外的信息。这实际上是我从QRubberBand得到的代码,除了必须使用event.screePos(),并且我必须将QRubberBand的构造函数设置为event.widget()而不是“this”,因为我认为QGraphicsItem不会从QWidget的?
有没有更好的方法来做到这一点?
感谢
答
我做了这个例子,我希望能帮助
我的自定义项目。
#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
和显示视图
#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();
}
什么是错误你有? – 2011-04-22 04:12:58