我有一个Qgraphicsscene作为一个类实现,然后我用QGraphicsScene :: mousePressEvent添加一个QGraphicsRectItem,这个项目也有一个QGraphicsRectItem :: mousePressEvent的实现,问题是rect项目中的事件传播到了场景,当我点击它添加一个新的矩形项目,但我想要的是,这个项目内的事件不会传播到场景,我尝试event->接受,但事件传播,我怎么能这样做?谢谢你的帮助。
这是我的qgraphicsscene代码:
#include "imageview.h"
ImageView::ImageView(QWidget *parent){
scene = new ImageScene(this);
setScene(scene);
//this->setMouseTracking(true);
this->setInteractive(true);
}
ImageScene::ImageScene(QWidget *parent){
current = NULL;
selection = new QRubberBand(QRubberBand::Rectangle,parent);
selection->setGeometry(QRect(10,10,20,20));
setSceneRect(0,0,500,500);
}
void ImageScene::mousePressEvent(QGraphicsSceneMouseEvent *event){
QGraphicsScene::mousePressEvent(event);
/*IGNORING THIS EVENT FROM QGRAPHICSRECTITEM*/
cout<<"image view"<<endl;
if(this->selectedItems().length() == 0){ /*WORKS BUT IN SOME IMPLEMENTATION IS A PROBLEM (WHEN I DELETE THE ITEM WITH A DELETE BUTTON THE EVENT IS FIRED AND ADD A NEW ITEM .)*/
origin = event->scenePos();
selection->show();
}
}
void ImageScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){
if(selection->isVisible() && selection->rect().width() >= 20 && selection->rect().height() >= 20){
QGraphicsScene::mouseReleaseEvent(event);
ResizableRect * rselection = new ResizableRect();
//selection->origin = event->scenePos();
//selection->grabMouse();
cout<<"add"<<endl;
this->addItem(rselection);
rselection->setPos(selection->pos());
rselection->setRect(0,0,selection->rect().width(),selection->rect().height());
}
selection->hide();
}
void ImageScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event){
QGraphicsScene::mouseMoveEvent(event);
if(selection->isVisible()){
QPoint rorigin(origin.x(),origin.y());
int xdes = event->scenePos().x();
int ydes = event->scenePos().y();
xdes = xdes > 0? xdes:0;
ydes = ydes > 0? ydes:0;
xdes = xdes < this->width()?xdes:this->width();
ydes = ydes < this->height()?ydes:this->height();
QPoint rdest(xdes,ydes);
selection->setGeometry(QRect(rorigin,rdest).normalized());
}
}
答案 0 :(得分:1)
与QWidgets相反,QGraphicsScene在子项目之前捕获事件。它在Qt文档中有描述。
为了正确使用它,请使用QGraphicsView而不是QGraphcisScene的重新实现。 在那里重新实现mousePressEvent。
此时您可以在鼠标指针下确定项目。 它就在那里 - 你可以调用QGraphicsView :: mousePressEvent(); 它不是 - 使用您的实现添加新项目。
它还允许您分离不同视图的行为。