繁体   English   中英

QTimer插槽没有被调用

[英]QTimer slot doesn't get called

我在MainWindow类中有一个QTimer ,但是没有调用update插槽。 我是QT新手。 我不知道会是什么。 connect()返回true ,我既没有从QT创建者的消息窗口中收到警告,也没有得到运行时错误。 就是行不通。

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";
}

您提供的代码有效。 我只是在一个空的默认GUI Qt项目中尝试过。

标题:

#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";
}

结果:

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

请确认在标头中将update()方法声明为插槽。 检查您是否没有忘记Q_OBJECT宏,是否包括必需的类。 问题可能来自您未在问题中显示的内容。

我和你有同样的问题。 只要确保您调用的函数(myUpdate())在头文件的插槽声明中即可

例如:

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

暂无
暂无

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

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