如何使用QT每隔15秒调用一次函数 [英] How to call a function after every 15 seconds using QT

查看:591
本文介绍了如何使用QT每隔15秒调用一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我的问题与此问题,但我无法从那里找到解决方案。谁能回答我的问题?

I know my question is similar to this QUESTION but i cant find solution from there. Can anyone give a breif answer to my problem?

我有这样的功能

void myWidget::showGPS()
{

/* This function will read data from text file
      that will continuouly change over time
           then process its data */

}

我想每次都调用此函数15-20秒,而无需使用将布尔值设置为true的快捷方法。

I want to call this function every 15-20 seconds without using Quick-and-dirty method of setting boolean to true .

有没有办法使用
QT信号和带有计时器的槽或类似的东西来实现此目的?

Is there any way to implement this using QT signal and slot with timer or something like that

推荐答案

方法 showGPS()应该放在 MyWidget 类。
然后,只需使用 QTimer 类。

The method showGPS(), should be made a slot of MyWidget class. Then on, its just a matter of using the QTimer class.

 QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), myWidget, SLOT(showGPS()));
    timer->start(15000); //time specified in ms

上面的代码每15秒调用一次showGPS()。
因为调用是周期性的,所以不必使用 setSingleShot()方法将计时器设置为单发模式。

The above code will call showGPS(), every 15 seconds. Since the call is periodic, you don't have to set the timer in one shot mode using the setSingleShot() method.

编辑:

这是一个简单的poc,可帮助您理解。.

This is a simple poc, to help you understand it..

#include <QApplication>
#include <QtGui>
#include <qobject.h>

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    MyWidget()
    {
        timer = new QTimer(this);
        QObject::connect(timer, SIGNAL(timeout()), this, SLOT(showGPS()));
        timer->start(1000); //time specified in ms
    }

public slots:
    void showGPS()
    {
        qDebug()<<Q_FUNC_INFO;
    }

private:
    QTimer *timer;
};


int main(int argc, char **args)
 {
    QApplication app(argc,args);
    MyWidget myWidget;


    return app.exec();
}

这篇关于如何使用QT每隔15秒调用一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆