There's many ways of doing what you want.
Subclassing is one of them.
Take a look at this example, here I use event filter to do what you want (compile and try it out):
#include "mainwindow.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPathItem>
#include <QEvent>
#include <QGraphicsSceneMouseEvent>
MainWindow
::MainWindow(QWidget *parent
) :
item( NULL )
{
this->scene->setSceneRect( 0, 0, 1000, 1000 );
this->setCentralWidget( this->view );
this->scene->installEventFilter( this );
}
MainWindow::~MainWindow()
{
}
{
switch( e->type() )
{
case QEvent::GraphicsSceneMousePress: {
pp.moveTo( event->scenePos() );
this->item->setPath( pp );
this->scene->addItem( this->item );
break;
}
case QEvent::GraphicsSceneMouseMove: {
if( this->item )
{
pp.lineTo( event->scenePos() );
this->item->setPath( pp );
}
break;
}
case QEvent::GraphicsSceneMouseRelease: {
this->item = NULL;
break;
}
default:
break;
}
return false;
}
#include "mainwindow.h"
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPathItem>
#include <QEvent>
#include <QGraphicsSceneMouseEvent>
MainWindow::MainWindow(QWidget *parent)
:
QMainWindow( parent ),
scene( new QGraphicsScene( this ) ),
view( new QGraphicsView( this->scene, this ) ),
item( NULL )
{
this->scene->setSceneRect( 0, 0, 1000, 1000 );
this->setCentralWidget( this->view );
this->scene->installEventFilter( this );
}
MainWindow::~MainWindow()
{
}
bool MainWindow::eventFilter( QObject* o , QEvent* e )
{
switch( e->type() )
{
case QEvent::GraphicsSceneMousePress:
{
QGraphicsSceneMouseEvent* event = static_cast< QGraphicsSceneMouseEvent* >( e );
QPainterPath pp;
pp.moveTo( event->scenePos() );
this->item = new QGraphicsPathItem();
this->item->setPath( pp );
this->scene->addItem( this->item );
break;
}
case QEvent::GraphicsSceneMouseMove:
{
if( this->item )
{
QGraphicsSceneMouseEvent* event = static_cast< QGraphicsSceneMouseEvent* >( e );
QPainterPath pp = this->item->path();
pp.lineTo( event->scenePos() );
this->item->setPath( pp );
}
break;
}
case QEvent::GraphicsSceneMouseRelease:
{
this->item = NULL;
break;
}
default:
break;
}
return false;
}
To copy to clipboard, switch view to plain text mode
Bookmarks