PDA

View Full Version : Painting the mouse trace in a QGraphicsItem



xtraction
15th February 2012, 14:33
Hello,

I have a QGraphicsView with a scene that displays an image. What I am trying to do now is when I click the mouse and move without un-clicking, I want to draw the mouse trace until the mouse button is released. So basically to draw with the mouse.

Could someone please guide me to what I need to do for this?

So far what I am trying to do is subclassing QGraphicsRectItem and from the mouse events of the QGV call my own functions in the GraphicsItem subclass passing as a parameter the QMouseEvent and handling things there.

I know I have to implement the paint event to draw, but I’m a bit lost how to approach this. I was thinking maybe getting the points of the trace and drawing small line segments in between, would this be a good possible way?

I appreciate any help. Thanks.

Spitfire
20th February 2012, 12:21
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)
:
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;
}

aamir_azad
9th February 2013, 10:08
Can this be done without mousepress event.

I want to draw where ever the mouse cursor moves (without clicking).!!!