I've created a small QT application that redraws a circle at a random position. What I would like to do is repeat the method a predetermined number of times that draws the circle every second using a QTimer.
I am not sure how to go about to this.
Here is my main.cpp
int main(int argc, char *argv[]) {
// initialize resources, if needed
// Q_INIT_RESOURCE(resfile);
srand (time(NULL));
QApplication app(argc, argv);
widget f;
f.show();
return app.exec();
}
widget.cpp
#include "widget.h"
widget::widget()
{
widget.setupUi(this);
}
void widget::paintEvent(QPaintEvent * p)
{
QPainter painter(this);
//**code
printcircle(& painter); //paints the circle
//**code
}
void paintcircle(QPainter* painter)
{
srand (time(NULL));
int x = rand() %200 + 1;
int y = rand() %200 + 1;
QRectF myQRect(x,y,30,30);
painter->drawEllipse(myQRect);
}
widget::~widget()
{}
widget.h
#ifndef _WIDGET_H
#define _WIDGET_H
class widget : public QWidget {
Q_OBJECT
public:
widget();
virtual ~widget();
public slots:
void paintEvent(QPaintEvent * p);
private:
Ui::widget widget;
};
#endif /* _WIDGET_H */
How would I go about creating a Qtimer to repeat the printcricle() method.
Thanks
You can create a timer in your widget class constructor as:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
I.e. it will call the widget's paint event every second.