您的位置:首页 > 编程语言 > Qt开发

Qt里通过传递函数指针实现动态绑定信号/槽

2015-04-03 23:02 453 查看
// 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();
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: