c++ - QTimer 插槽没有被调用

标签 c++ windows qt qtimer

我在 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

实现:

#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() 方法是否在 header 中声明为插槽。检查您是否忘记了 Q_OBJECT 宏,是否包含了必需的类。该问题可能来自于您在问题中未显示的内容。

关于c++ - QTimer 插槽没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809507/

相关文章:

c++ - 在 C++ 中获取总核心数量的跨平台代码片段是什么?

c++ - 链表的 Lambda 长度

c++ - 带有标准输出重定向的 `boost::process` 在 Ubuntu 16 中随机失败

python - 如何更改标题数据

c++ - 使用 Qt 获取页面内容

具有奇怪行为的 C++ std::vector push_back

windows - 如何以编程方式显示文件的 shell 提示(在资源管理器中悬停文件时出现的文本)

c++ - MS 蓝牙堆栈文档

windows - 单击关闭按钮关闭批处理脚本时如何运行批处理命令

c++ - QTimer::singleShot() 在给定对象的父类中查找指定的槽,而不是对象本身