如何使用QTimer

时间:2012-07-25 14:17:43

标签: qt timer

在Qt中,我试图设置一个QTimer,每秒调用一个名为“更新”的函数。这是我的.cpp文件:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTimer>
#include "QDebug"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

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

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::update()
{
    qDebug() << "update";
}

和主要:

#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

该项目正在构建,但它没有执行更新,因为“更新”行没有显示在任何地方......有人看到我做错了吗?

3 个答案:

答案 0 :(得分:13)

其他方式是使用内置方法启动计时器&amp;事件TimerEvent。

部首:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    int timerId;

protected:
    void timerEvent(QTimerEvent *event);
};

#endif // MAINWINDOW_H

来源:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timerId = startTimer(1000);
}

MainWindow::~MainWindow()
{
    killTimer(timerId);
    delete ui;
}

void MainWindow::timerEvent(QTimerEvent *event)
{
    qDebug() << "Update...";
}

答案 1 :(得分:12)

  1. 优良作法是让QTimer的父母使用Qt的内存管理系统。

  2. update()是一个 QWidget 函数 - 是您要调用的是什么? http://qt-project.org/doc/qt-4.8/qwidget.html#update

  3. 如果数字2不适用,请确保您尝试触发的功能被声明为标题中的一个插槽。

  4. 最后,如果这些都不是您的问题,那么了解您是否遇到任何运行时连接错误会很有帮助。

答案 2 :(得分:0)

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

如果我们运行代码:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

相关问题