再会。在 Qt 中制作了一个简单的计时器类
计时器.h:
#include <QObject>
#include <QTimer>
#include <udp.h>
#include <stdio.h>
class TimerUdp: public QObject
{
public:
TimerUdp(Udp *udp_p);
~TimerUdp();
private:
QTimer *timer;
Udp *udp;
private slots:
void slot_timer();
};
计时器.cpp:
#include "timer.h"
TimerUdp::TimerUdp(Udp *udp_p)
{
udp = udp_p;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(slot_timer()));
timer->start(1000);
}
TimerUdp::~TimerUdp()
{
delete timer;
delete udp;
}
void TimerUdp::slot_timer()
{
printf("tttt\n");
}
主.cpp:
#include <QCoreApplication>
#include <stdio.h>
#include "udp.h"
#include "timer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Udp *udp = new Udp();
udp->SetParams("172.17.172.133", 1234, 1235);
TimerUdp *timer = new TimerUdp(udp);
return a.exec();
}
启动后,定时器不工作并发出警告:
QObject::connect: 没有这样的插槽 QObject::slot_timer()
为什么 connect 试图在 QObject 类中而不是在 TimerUdp 类中找到插槽?如何使它正确,以便它在 TimerUdp 中寻找一个插槽?
将宏 Q_OBJECT 添加到 timer.h:
正如上面评论中所建议的,我关闭了 qt,删除了程序集,重新构建了它。现在一切正常。