简体   繁体   中英

QTimer slot doesn't get called

I have a QTimer in MainWindow class but the update slot doesn't get called. I'm new to QT. I have no idea what it would be. connect() return true and I get neither warning from messages window in QT creator nor run-time errors. It just doesn't work.

void MainWindow::on_startBtn_clicked()
{
    QTimer *timer = new QTimer(this);
    qDebug() << connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(500);
}

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

The code you provided is valid. I just tried it in an empty default GUI Qt project.

Header:

#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 slots:
    void on_startBtn_clicked();
    void update();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

Implentation:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>
#include <QDebug>

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

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

void MainWindow::on_startBtn_clicked()
{
    QTimer *timer = new QTimer(this);
    qDebug() << connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(500);
}

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

And the result:

Démarrage de E:\projects\playground\build-qt_gui_test-Desktop_Qt_5_5_0_MSVC2013_64bit-Debug\debug\qt_gui_test.exe...
true
update() called
update() called
update() called
update() called
update() called
update() called
update() called
E:\projects\playground\build-qt_gui_test-Desktop_Qt_5_5_0_MSVC2013_64bit-Debug\debug\qt_gui_test.exe s'est terminé avec le code 0

Please verify that the update() method is declared in your header, as a slot. Check that you didn't forget Q_OBJECT macro, you included required classes. The issue probably come from something you didn't show in your question.

I have the same problem as you. Just make sure that the function that you call ( myUpdate() ) is in slot declaration in the header file

for example:

class MainWindow : public QMainWindow
{
    Q_OBJECT


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

    void showEvent(QShowEvent *event);

    //void myUpdate();  // <------          NEVER PUT INHERE
public slots:           // <------          MUST BE IN HERE
    void myUpdate();    // <------
private:
    Ui::MainWindow *ui;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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