我创建了一个小的QT应用程序,它可以在任意位置重新绘制一个圆。我想要做的是重复这个方法--一个预定的次数,它每秒钟使用一个QTimer绘制圆圈。
我不知道该怎么做。
这是我的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 */我将如何创建一个Qtimer来重复print板球()方法。
谢谢
发布于 2014-04-18 20:12:06
您可以在小部件类构造函数中创建定时器,如下所示:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);也就是说,它将每秒钟调用小部件的画图事件。
发布于 2014-04-19 02:05:38
是的,为了实现这一点,您的代码中有几件事情需要修改:
update插槽的连接,以便事件循环计划重绘。为了实现上述所有这些,您的代码将变成如下所示:
widget.cpp
#include "widget.h"
#include <QTimer>
// Could be any number
const static int myPredeterminedTimes = 10;
widget::widget()
: m_timer(new QTimer(this))
, m_count(0)
{
widget.setupUi(this);
connect(m_timer, SIGNAL(timeout()), SLOT(update()));
timer->start(1000);
}
void widget::paintEvent(QPaintEvent * p)
{
QPainter painter(this);
//**code
printcircle(& painter); //paints the circle
//**code
}
void widget::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 QTimer;
class widget : public QWidget {
Q_OBJECT
public:
widget();
virtual ~widget();
public slots:
void paintEvent(QPaintEvent * p);
private:
Ui::widget widget;
private:
QTimer *m_timer;
int m_count;
};
#endif /* _WIDGET_H */https://stackoverflow.com/questions/23160374
复制相似问题