![](/img/trans.png)
[英]Passing event from QGraphicsScene to QGraphicsItem in C++ with Qt
[英]stop event propagation from QGraphicsItem to QGraphicsScene QT
我有一个实现为类的Qgraphicsscene,然后使用QGraphicsScene :: mousePressEvent添加了QGraphicsRectItem,该项目也有QGraphicsRectItem :: mousePressEvent的实现,问题是rect项目中的事件会传播到场景中,何时我单击它添加了一个新的rect项,但是我想让该项中的事件不会传播到场景,我尝试event-> accept,但是该事件被传播了,我该怎么办? 谢谢你的帮助。
这是我的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());
}
}
与QWidgets相反,QGraphicsScene在子项之前捕获事件。 Qt文档中对此进行了描述。
为了正确使用它,请使用QGraphicsView的重新实现而不是QGraphcisScene。 在那里重新实现mousePressEvent。
此时,您可以确定鼠标指针下的项目。 它在那里-您可以仅调用QGraphicsView :: mousePressEvent(); 并非如此-使用您的实现来添加新项目。
它还允许您分隔不同视图的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.