PDA

View Full Version : Draw shape on mousepress?



Niamita
6th June 2011, 14:07
Hi
i want to draw a shape when the particular area is pressed.
I want to ask that how to combine paintEvent() and mousePressEvent() method to implement above.

mvuori
6th June 2011, 15:50
In your mousePressEvent() get the coordinates of the event and store them in some variable. Then call this->update(), which will launch your paintEvent() where you can do the drawing or call your draqing method.

helloworld
6th June 2011, 16:08
There are numerous ways to achieve this and you'll need to provide a bit more information to get some useful help. For example, what is a "particular area" in this case?

Let's say you are creating a drawing program, adding shapes every time the user clicks a specific location; then you could use a QGraphicsScene and simply add items to that scene inside the mousePressEvent.

Or, if you have a layout with several widgets and simply want to toggle the visible state of each widget when it is clicked, then it's probably better to reimplement paintEvent and mousePressEvent in that specific widget and have a member variable that keeps track of whether or not the widget is "active".


void paintEvent(QPaintEvent *)
{
QPainter painter(this);
if (m_active)
painter.drawPath(somePath);
}

void mousePressEvent(QMouseEvent *)
{
m_active = !m_active;
update();
}

Or, (most likely) if you have a single widget and want to draw a shape where the mouse press event occurs; like mvuori said in previous post.

Again, it all depends on what you mean by "particular area" and what the rest of you application looks like.

Niamita
7th June 2011, 07:48
hi helloworld
i do the same as u say and i am getting which i wanted to do , after pressed the painted shape is permanent on the area while i want that after pressing the area the painted shape visible only for few seconds . How i can do this.
Does anybody can tell me how to do this?

Santosh Reddy
7th June 2011, 07:59
You can add a timer and clear it when not required



void mousePressEvent(QMouseEvent *)
{
m_active = true;
update();
startTimer(2000); //2 seconds
}

void timerEvent(QTimerEvent* event)
{
m_active = false;
update();
killTimer(event->timerId());
}