我正在尝试使用 QTimer 作为信号的发送者来连接信号和插槽。不幸的是,当我编译下面的代码时,程序运行,但我收到警告:“在 game.cpp 中没有这样的插槽 QObject::flip()”。
看来我的插槽没有正确定义。使用关于 QTimer 的Youtube 教程,听起来好像我需要在游戏类中添加“Q_OBJECT”宏(这在下面被注释掉了)。但是,如果我取消注释,程序将无法编译,并提供错误消息:“未定义对 'vtable for Game' 的引用”。
如何正确连接定时器的信号和插槽?
游戏.h
#ifndef GAME_H
#define GAME_H
#include "player.h"
#include <QtCore>
class Game : public QObject {
//Q_OBJECT
public:
Game();
void timed_job();
public slots:
void flip();
private:
bool is_game_on;
QTimer *timer;
Player player_1;
Player player_2;
Player player_3;
};
#endif // GAME_H
游戏.cpp
#include "game.h"
#include <QtCore>
Game::Game() {
is_game_on = true;
}
void Game::timed_job() {
timer = new QTimer(this);
timer->start(1000);
connect(timer, SIGNAL(timeout()), this, SLOT(flip()));
}
void Game::flip() {
if(is_game_on == true) {
is_game_on = false;
}
else {
is_game_on = true;
}
}