2012-10-20 82 views
0

我有一個Qgraphicsscene實現爲一個類,然後我使用QGraphicsScene :: mousePressEvent添加一個QGraphicsRectItem,這個項目也有一個QGraphicsRectItem :: mousePressEvent的實現,問題在於事件在rect項目傳播到現場,當我點擊它是添加一個新的rect項目,但我想要的是這個項目內的事件不傳播到現場,我嘗試事件 - >接受,但事件傳播,我怎麼能這樣做?謝謝你的幫助。停止事件從QGraphicsItem傳播到QGraphicsScene QT

這裏是我的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()); 
    } 

} 
+2

在代碼中調用event-> accept()的地方在哪裏? – jmk

+0

在ResizableRect類中的mousePressEvent函數中,該類擴展了QGraphicsRectItem。 –

+1

請參閱[這裏](http://qt-project.org/doc/qt-4.8/QGraphicsScene.html#event-handling-and-propagation)和[here](http://qt-project.org/doc /qt-4.8/qgraphicsitem.html#events)。希望能幫助到你。 – sashoalm

回答

0

對面QWidgets,QGraphicsScene抓住前子項的事件。它在Qt文檔中有描述。

爲了正確的工作,使用QGraphicsView而不是QGraphcisScene的重新實現。 重新實現mousePressEvent那裏。

那時您可以確定鼠標指針下的項目。它可以在那裏 - 你可以調用QGraphicsView :: mousePressEvent(); 它不是 - 使用您的實施添加新項目。

它還允許你分開不同視圖的行爲。