Pregunta

According to the docs, QGraphicsSceneEvent::widget() returns a QWidget. Isn't the widget always going to be a QGraphicsView, though (or null)?

I would assume so, except then I don't understand why the devs wouldn't have just made it QGraphicsSceneEvent::view().

The reason I'm asking is that in my subclassed QGraphicsScene, I have overridden QGraphicsScene::mousePressEvent() and I want to know which view originated the event--I'm wondering if it's safe to static cast widget() to a QGraphicsView, or if it's conceivable that some other widget could have created the event.

¿Fue útil?

Solución

As it turns out, QGraphicsSceneEvent::widget() returns the viewport widget, not the QGraphicsView. If you want the QGraphicsView, you would need to use: event->widget()->parent().

Otros consejos

Documentation page you refered mentions the QGraphicsView as a target of events:

When a QGraphicsView receives Qt mouse, keyboard, and drag and drop events (QMouseEvent, QKeyEvent, QDragEvent, etc.), it translates them into instances of QGraphicsSceneEvent subclasses and forwards them to the QGraphicsScene it displays. The scene then forwards the events to the relevant items.

However, if you doubt that QGraphicsSceneEvent::widget() always returns QGraphicsView, or you relay that it should always be a QGraphicsView you can check that by using qobject_cast:

QGraphicsView *view = qobject_cast<QGraphicsView *>(event->widget();
if (view) {
    // Handle the event
} else {
    // This is something that I do not expect.
    // ..
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top