0
votes

I dont konw how to connect timers timeout and mouseevent class. I need to draw a new particle in "waterfield" (qwidget) when mouse button is pressed every 200 ms. When i release the button painter should not draw more. I got this in my constructor:

timertap.setInterval(200);
timertap.start();
connect(&timertap,SIGNAL(timeout()),this,SLOT(taptap()));
setMouseTracking(true);

In my class there are slot taptap() and bool tapenable.

This is code which is not working:

void waterfield::taptap()
{
    QMouseEvent *e;
    if(tapenable && e->button()==Qt::LeftButton)
    {
        particle p;
        int x=e->pos().x();
        int y=e->pos().y();
        p.position.y=y;
        p.position.x=x;
        zbiorczastek.push_back(p);
        painter.drawEllipse(x,y,particlesize,particlesize);
    }
}

void waterfield::mousePressEvent(QMouseEvent *e)
{
    tapenable=true;
}

void waterfield::mouseReleaseEvent(QMouseEvent *e)
{
    tapenable=true;
}

After i click program crashs. I think its a good idea to do it this way. Timer is set to 200ms, so every 200ms signal timeout is set and slot taptap recive it and check if tapenable is set by mousepressevent or reset by mousereleaseevent. Any suggestions?

2

2 Answers

1
votes

You declare a pointer in waterfield::taptap():

QMouseEvent *e;

without initializing it, so the program crashes as using an unitialized pointer is undefined behaviour.

Apart from this, you're using QMouseEvent the wrong way. You seem to think that this object represents some global mouse state that is available through any object of type QMouseEvent. This is not true. A QMouseEvent object that actually represents the current mouse state is caught by slots that take QMouseEvent *e as an argument, such as mousePressEvent().

You need to call the taptap() method from mousePressEvent(QMouseEvent *e), and pass mousePressEvent's QMouseEvent *e argument to the taptap() function. You also should start the timer in the mousePressEvent() slot and stop it inside the mouseReleaseEvent().

1
votes

After i click program crashs.

You need to learn to debug your code instead of asking others to do it for you.

You should not be drawing in a slot connected to a timer; you should do it in the paintEvent function. In the timer slot, you simply add the particle and call update(). Then you start the timer in mousePressEvent and stop it in mouseReleaseEvent. You also don't need setMouseTracking, because this is done automatically while you keep the mouse button pressed.