PDA

View Full Version : draw point with mouseevent



konvex
11th November 2008, 11:08
Hallo, I'm a beginner and use Qt 4.4.3.
I would like to draw a point in a scene when i click in the scene. but my program draws a point without clicking, but the point should appear if i click.
I hope somebody can help me.
Here is my program:



class StarItem : public QGraphicsItem
{
public:
StarItem( QGraphicsItem *parent = 0 ) : QGraphicsItem(parent) {}
void paint( QPainter *, const QStyleOptionGraphicsItem *, QWidget *widget=0 );
QRectF boundingRect() const;
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *e);
void mouseMoveEvent(QGraphicsSceneMouseEvent *e);
private:
QPoint position;
int posx;
int posy;
bool shower;
};





#include "staritem.h"

void StarItem::mousePressEvent(QGraphicsSceneMouseEvent *e)
{
if (e->button() == Qt::LeftButton)
{
shower=true;
QPoint position = e->screenPos();

posx = position.x();
posy = position.y();
update();
}
return QGraphicsItem::mousePressEvent(e);
}

void StarItem::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
position = e->screenPos();
return QGraphicsItem::mouseMoveEvent(e);
}


void StarItem::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
Q_UNUSED( option );
Q_UNUSED( widget );

QPen pen(Qt::black, 6, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
painter->setPen(pen);

if(shower=true)
{
painter->drawPoint(posx,posy);
}

}

QRectF StarItem::boundingRect() const
{
return QRectF( 0, 0, 100, 100 );
}


I have no idea what's wrong...

draftpunk
11th November 2008, 15:06
Hi,

I just saw the problem:



if(shower=true)
{
painter->drawPoint(posx,posy);
}

I think you want:


shower == true


Have fun!

-draftpunk

konvex
11th November 2008, 19:47
Thanks for the answer.
but I now the problem, I have to draw in the graphicscene and not in der item...
But I tried another way without solution: Now I try to move a ellipse that is in the scene, but in my program there's a small mistake(I think), what I don't see...
I think it's a mistake in the main function?!
Please help...

main.cpp


int main(int argc,char **argv)
{
QApplication app(argc,argv);
QGraphicsScene scene;
QGraphicsView view;

StarItem item(100,100,10,10);
scene.addItem(&item);

view.setGeometry(100, 100, 500, 500);
view.setScene(&scene);
view.show();
return app.exec();
}

staritem.h


class StarItem : public QGraphicsEllipseItem
{
public:
StarItem (int x,int y,int w,int h) : QGraphicsEllipseItem (x,y,w,h) {}
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *e);
};

staritem.cpp


void StarItem::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
setRect((e->scenePos().x()),(e->scenePos().y()),10,10);
}


Thanks for every answer.

aamer4yu
12th November 2008, 04:49
what are you trying to achieve ? If you want to move the item, you dont need to code !!
Qt does it for u.. just have a look at QGraphicsItem::setFlag with value QGraphicsItem::ItemIsMovable :)