繁体   English   中英

如何同时处理从QGraphicsView和QGraphicsItem捕获的鼠标事件?

[英]How to handle mouse events captured from QGraphicsView and QGraphicsItem at the same time?

在此代码中,我需要在ItemcustomGraphicsView mousePressEvent(..)中执行不同的操作。 在鼠标事件处理程序的重新定义QGraphicsView继承类与产生干扰QGraphicsItem如何点击的动作分离Itemview ,使他们能够给出一个不同的行为?

class CustomGraphicsView: public QGraphicsView 
{
...
protected:
    void mousePressEvent(QMouseEvent * event);
};

class Item: public QGraphicsItem
{
protected:
   void mousePressEvent(QMouseEvent * event);
};

class customWidget: public QWidget 
{
public:
customWidget(QWidget * parent = 0) ;
...
private:
    customGraphicsView * view ;
    Item * item ;
};

customWidget::customWidget(QWidget* parent)
    :QWidget(parent)
{
view = new customGraphicsView(this) ;
item = new item; 

view->addItem(item) ;

}

您还需要了解QGraphicsView,QGraphicsScene和场景中任何项目之间的事件处理。 QGraphicsView首先获取事件,将其转换为场景事件,然后场景将它们传递给适当的项目。 如果您没有看到预期的事件,则可能是因为您首先在其他地方拦截了该事件。 我发现将调试语句放入每个事件处理程序中非常有用,这样我就可以看到事件进入何处以及事件没有进入何处。

首先 ,您应该对QGraphicsItem使用QGraphicsSceneMouseEvent而不是QMouseEvent

然后为每个mousePressEvent编写自己的实现,例如:

void Item::mousePressEvent(QGraphicsSceneMouseEvent *event) {
   QGraphicsItem::mousePressEvent(event);
// do everything you was going to
}

void CustomGraphicsView::mousePressEvent(QMouseEvent *event) {
   QGraphicsView::mousePressEvent(event);
// do everything you was going to
}

感谢您的回答,但是我不得不删除QGraphicsItem鼠标事件并仅通过QGraphicsView这样实现代码

void CustomGraphicsView::mousePressEvent(QMouseEvent * event)
{
    Item * pressedItem ;

    pressPoint = event->pos();

    if(scene())
    {
        if (!items().isEmpty())
        {
            QPointF scenePoint = mapToScene(event->pos()) ;

            QGraphicsItem * item = scene()->itemAt(scenePoint, transform());


            if(pressedItem = dynamic_cast<Item*>(item))
            {
                //code for item press, instead of using QGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
                 pressedItem->setColor(Qt::red); 
           }
        }

     }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM