QGraphicsSvgItem and mousePressEvent troubles
-
The following program draws a red SVG rectangle in a white window.
When you click on the white area, you'll see a messagebox with the text "QGraphicsView (White)".
When you click on the red rectangle, I'd expect to see a messagebox with the text "QGraphicsSvgItem (Red)".
However, I see "QGraphicsView (White)" instead.
Can anyone point out what I'm doing wrong here ?[code]
//------------------------------------------------------------------------------
#include <QtGui/QApplication>
#include <QtGui/QGraphicsView>
#include <QtGui/QMessageBox>
#include <QtGui/QMouseEvent>
#include <QtSvg/QGraphicsSvgItem>
#include <QtSvg/QSvgRenderer>
//------------------------------------------------------------------------------
class View : public QGraphicsView
{
Q_OBJECT
public:
View() : QGraphicsView()
{
}protected:
void mousePressEvent(QMouseEvent *event)
{
QMessageBox::warning(0, "QGraphicsView (White)",
"QGraphicsView (White)",
QMessageBox::Ok,
QMessageBox::Ok);
}
};
//------------------------------------------------------------------------------
class SvgItem : public QGraphicsSvgItem
{
public:
SvgItem(QGraphicsItem * p = NULL ) :
QGraphicsSvgItem( p )
{
setFlag( QGraphicsItem::ItemIsSelectable );
setFlag( QGraphicsItem::ItemIsMovable );QSvgRenderer* mySvgRenderer;
QByteArray svgData = QByteArray("<svg><rect x="0" y="0" width="50" height="50" fill="red" stroke="black" /></svg>");
mySvgRenderer = new QSvgRenderer(svgData, this);QRect svgSize = mySvgRenderer->viewBox();
this->setSharedRenderer(mySvgRenderer);}
~SvgItem()
{
}
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
QGraphicsItem::mousePressEvent(event);
QMessageBox::warning(0, "QGraphicsSvgItem (Red)",
"QGraphicsSvgItem (Red)",
QMessageBox::Ok,
QMessageBox::Ok);
}
};
//------------------------------------------------------------------------------
#include "main.moc"
//------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
QApplication app(argc, argv );View * view = new View();
QGraphicsScene * scene = new QGraphicsScene( 0, 0, 150, 150 );
SvgItem * rect = new SvgItem();
scene->addItem( rect );rect->setAcceptDrops( true );
rect->setAcceptHoverEvents( true );
rect->setPos(50,50);view->setScene( scene );
view->show();return( app.exec() );
}
//------------------------------------------------------------------------------
[/code] -
This is easy to understand. QGraphicsView is a QWidget, but QGraphicsSvgItem is not a QWidget, it just a item located in QGraphicsScene.
QGraphicsView(Receive mouseEvent) ==>QGraphicsScene ==> QGraphicsXXXItem
In your View class, you have override the mousePressEvent, but you forget to call mousePressEvent of it's base class.