Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

c++ - How to call a function after every 15 seconds using QT

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?

I have a function like this

void myWidget::showGPS()
{

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

}

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

Edit:

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...