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();
}
相关文章推荐
- Qt实现读取显示obj文件——动态绑定纹理与消除纹理
- QT 进行动态绑定信号槽时,如何正确找到当前操作的控件?
- php 通过__callStatic魔术方法实现方法的动态创建和延迟绑定
- android通过绑定service实现歌曲播放,并把歌词以不同色调动态绘出
- vue.js通过子组件通信和父子组件通信实现动态表单动态绑定事件(适合交互系统统一使用)
- 利用TreeView控件动态生成无限级树(续:通过绑定动态xml文件)
- 通过使页面动态加载不同CSS实现多界面
- 通过动态创建表来实现成绩存放
- [转]VS2005下水晶报表实现动态数据源绑定
- JBPM通过AssignmentHandler绑定自定义用户模型实现用户授权
- 使用反映实现前端WEB窗口控件与后台数据库类对象的动态绑定
- 动态改变绑定后的DataGrid的列宽(测试通过)
- 在QT中通过摄像头动态显示图片
- 利用TreeView控件动态生成无限级树(续:通过绑定动态xml文件)(转)
- QT中关于信号与槽机制的实现原理
- 通过函数指针动态调用 dll 中的函数
- 如何通过动态生成Html灵活实现DataGrid分类统计的界面显示功能
- 通过使页面动态加载不同CSS实现多界面
- ASP.NET中GridView动态绑定数据实现编辑更新
- [转]VS2005下水晶报表实现动态数据源绑定