// test.h
#include <QObject>
class QTimer;
class Test:public QObject
{
Q_OBJECT
public:
Test(QObject * parent = 0);
~Test();
void startTimer(int interval);
void connectQTimer(void(Test::*pf)());
public slots:
void onTimeout();
void onPrintOut();
private:
QTimer *m_timer;
};
#endif // TEST
// test.cpp
#include <QTimer>
#include <QDebug>
#include "test.h"
Test::Test(QObject *parent)
: QObject(parent)
{
m_timer = new QTimer(this);
}
Test::~Test()
{
m_timer->deleteLater();
m_timer = NULL;
}
void Test::startTimer(int interval)
{
m_timer->start(interval);
// timer->setSingleShot(true);
}
void Test::connectQTimer(void (Test::*pf)())
{
connect(m_timer, &QTimer::timeout, this, pf);
// 失败方法1
// connect(m_timer, SIGNAL(timeout()),this, SLOT(pf));
// 失败方法2
// connect(m_timer, SIGNAL(timeout()),this, SLOT(*pf));
// 失败方法3
// connect(m_timer, SIGNAL(timeout()),this, SLOT((this->*pf)()));
}
void Test::onTimeout()
{
qDebug()<<"onTimeout()called...\n";
}
void Test::onPrintOut()
{
qDebug()<<"onPrintOut()called...\n";
}
// main.cpp
#include <QCoreApplication>
#include <QTimer>
#include "test.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Test test;
/*** 第一种方式传递函数指针 ***/
test.connectQTimer(&Test::onTimeout);
test.connectQTimer(&Test::onPrintOut);
/*** 第二种方式传递函数指针 ***/
// void(Test::*pf)() = &Test::onTimeout;
// test.connectQTimer(pf);
// void(Test::*pp)() = &Test::onPrintOut;
// test.connectQTimer(pp);
test.startTimer(5000);
return a.exec();
}