我试图做到这一点,以便如果用户单击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
并显示 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();
}