3

我创建了一个小型 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();
}

小部件.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()
{}

小部件.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 来重复 printcicle() 方法。

谢谢

4

2 回答 2

2

您可以在小部件类构造函数中创建一个计时器,如下所示:

 QTimer *timer = new QTimer(this);
 connect(timer, SIGNAL(timeout()), this, SLOT(update()));
 timer->start(1000);

即它将每秒调用小部件的绘制事件。

于 2014-04-18T20:12:06.143 回答
1

是的,为了实现这一点,您需要在代码中修改一些内容:

  • 转发声明一个 QTimer

  • 添加 QTimer 成员

  • 包括 QTimer 标头。

  • 在小部件类的构造函数中设置一个连续的 QTimer。

  • 确保您设置了与update插槽的连接,以便事件循环安排重绘。

  • 您需要为预定时间添加一个计数器,因为 QTimer 中没有内置这样的功能。

  • 您需要将该变量初始化为零。

  • 您需要在每个插槽调用中增加它。

  • 您需要停止为 QTimer 发出超时信号。

为了实现上述所有目标,您的代码将变成这样:

小部件.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()
{}

小部件.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 */
于 2014-04-19T02:05:38.313 回答