繁体   English   中英

QPimer与QPaintEvent

[英]QTimer with QPaintEvent

我创建了一个小型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来重复printcricle()方法。

谢谢

您可以在窗口小部件类构造函数中创建一个计时器:

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

即它会每秒调用小部件的绘画事件。

是的,为了完成这个,你需要在代码中修改一些东西:

  • 转发声明QTimer

  • 添加QTimer成员

  • 包括QTimer标头。

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

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

  • 您需要在预定时间内添加计数器,因为QTimer中没有内置此功能。

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

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

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

为了实现上述所有目标,您的代码将变为如下所示:

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 */

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM