信号与槽
背景:
面向过程
模块之间低耦合设计(高内聚)。
函数调用:
直接调用
回调调用(低耦合)
面向对象
模块之间低耦合设计(高内聚)
对象调用
直接调用
接口调用
QT:
信号与槽解决问题:
对象的成员变量调用?
对象的成员函数调用?
案例:
窗体,有一个文本框
线程,每个一秒改变文本框
问题:
线程类访问窗体组件比较麻烦,需要传递。
在QT中,使用线程程序可能不工作。
代码:
#include<QApplication>
#include “shake.h”
int main(int args , char **argv)
{
QApplication app(args , argv);
ShakeForm dlg;
dlg.setVisible(true);
return app.exec();
}
shake.h
#ifndef SHAKE_H
#define SHAKE_H
#include<QDialog>
#include<QLineEdit>
#include “mythread.h”
class ShakeForm : public QDialog
{
public:
ShakeForm(QWidget * parent=NULL);
~ShakeForm();
private:
QLineEdit *txt;
ShakeThread *th;
};
#endif
shake.cpp
#include “shake.h”
ShakeForm::ShakeForm(QWidget *parent)
{
txt = new QLineEdit(this);
this->resize(400,300);
txt->resize(100,30);
txt->move(10,10);
th=new ShakeThread(txt);
th->start();
}
ShakeForm::~ShakeForm()
{
delete txt;
}
mythread.h
#ifndef SHAKE_THREAD_H
#define SHAKE_THREAD_H
#include<pthread.h>
#include<QLineEdit>
class ShakeThread
{
public:
pthread_t tid;
static void * s_run(void *);
QLineEdit *m_txt;
private:
ShakeThread(QLineEdit *txt);
void start();
virtual void run();
};
#endif
mythread.cpp
#include “mythread.h”
#include<unistd.h>
#include<math.h>
ShakeThread::ShakeThread(QLineEdit *txt)
{
m_txt=txt;
}
void *ShakeThread::s_run(void * data)
{
ShakeThread *st=(ShakeThread*)da