PDA

View Full Version : QGraphicsView drawing



vermarajeev
4th April 2007, 12:26
Hi guys,
I have written the given below sample program. I have two questions

1) I draw some lines (straight lines). Why the coordinates of the line gets changed???
2) The line should appear like rubberBand on mouseMoveEvent too . How to achieve it???


class graphicView : public QGraphicsView
{
Q_OBJECT
public:
graphicView(QGraphicsScene* s);
~graphicView(){}
private:
QPointF m_firstPt;
QPointF m_lastPt;
QGraphicsLineItem* m_edgeItem;
QGraphicsScene* m_canvas;
QVector<QLineF> m_vectorLine;
protected:
void mousePressEvent( QMouseEvent* e );
void mouseMoveEvent( QMouseEvent* e );
void mouseReleaseEvent( QMouseEvent* e );
void drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[]);


};

graphicView::graphicView(QGraphicsScene* s)
:QGraphicsView(s), m_canvas(s){
m_edgeItem = new QGraphicsLineItem( 0, m_canvas );
}

void graphicView::mousePressEvent( QMouseEvent* e ){
m_firstPt = e->pos();
m_lastPt = e->pos();
}
void graphicView::mouseMoveEvent( QMouseEvent* e ){
m_lastPt = e->pos();
}
void graphicView::mouseReleaseEvent( QMouseEvent* e ){
m_lastPt = e->pos();
m_edgeItem->setLine( QLineF( m_firstPt, m_lastPt ) );
m_vectorLine << QLineF( m_firstPt, m_lastPt );
}
void graphicView::drawItems(QPainter *painter,
int numItems,
QGraphicsItem *items[],
const QStyleOptionGraphicsItem options[]){
painter->setPen(Qt::black );
painter->drawLines( m_vectorLine );
}

Thanks

JonathanForQT4
4th April 2007, 14:44
first off, thanks for trying to help with my thread :)

1) When I get positions in my code I always do (for instance):
m_firstPt = mapToScene(e->pos());

this sets the m_firstPt to the place where the mouse is in terms of scene coordinates....and since you are drawing to m_canvas, I think that should help out a little... :)

also make sure that in graphicView class you do the following: m_canvas = new QGraphicsScene(this);

So to answer your question...this is possibly why the placement on the scene (aka canvas) may look weird? If this doesn't help, please say how the lines get changed...

2) you want the lines to appear like a rubberband? Then set the pen of m_edgeItem to a dotted line....using: setPen(QPen)

For what it's worth in my program I don't re-implement drawItems.....they should be drawn automatically when you add them to the scene.

hth.

Cheers,

Jonathan