**
1.信号槽
**
信号槽是Qt对象间通讯的方法,主要通过connect()函数连接信号函数和槽函数进行通讯
connect() 是QObject类的一个静态函数;
static QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection);
Qt信号槽的基本使用方法
send : 发送对象的指针
receiver: 接收/处理信号对象的指针
1. 使用宏定义
connect(sender,SIGNAL(signals()),receiver,SLOT(slot()));
2.使用函数指针
connect(sender,&ClassName::signal,receiver,&ClassName::slot);
3.重载函数指针
connect(this,QOverload<>::of(&ClassName::signal),this,QOverload<>::of(&ClassName::slot);
4.匿名函数
connect(sender,&ClassName::signal,receiver,[=]{
// 函数内容;
});
具体代码简单的实现;
#include "connectdispaly.h"
#include <QDebug>
ConnectDispaly::ConnectDispaly(QWidget *parent)
: QWidget(parent)
, m_pBtn(new QPushButton("QPushButton",this))
, m_pLineEdit(new QLineEdit(this))
{
// 1. 宏定义
connect(m_pBtn,SIGNAL(clicked()),m_pLineEdit,SLOT(clear()));
// 1. 函数指针
connect(m_pBtn,&QPushButton::clicked,m_pLineEdit,&QLineEdit::clear);
// 1.函数重载
connect(this,QOverload<int>::of(&ConnectDispaly::s_setIndex),this,QOverload<int>::of(&ConnectDispaly::getIndex));
//connect(this,QOverload<QString>::of(&ConnectDispaly::s_setIndex),this,QOverload<QString>::of(&ConnectDispaly::getIndex));
//4.匿名函数
connect(m_pBtn,SIGNAL(clicked()),this,[]{
qDebug()<<"lamda";
});
}
//
void ConnectDispaly::getIndex(int index){
qDebug()<<QString("%1").arg(index);
}
void ConnectDispaly::getIndex(QString &str){
qDebug()<<str;
}
宏定义
**`宏定义是Qt4的版本`**
#define SLOT(name) "1"#name
#define SIGNAL(name) "2"#name
信号槽的连接方式
bool QObject::connect ( const QObject * sender, //对象
const QMetaMethod & signal, //信号
const QObject * receiver, //接收者
const QMetaMethod & method, //槽函数
Qt::ConnectionType type = Qt::AutoConnection //连接类型 )
信号的取消连接 用的比较少
bool QObject::disconnect ( const QObject * sender,
const QMetaMethod & signal,
const QObject * receiver,
const QMetaMethod & method )
信号槽的五种连接方式
enum ConnectionType {
AutoConnection, // 默认连接方式 单线程 DirectConnection 多线程 DirectConnection
DirectConnection, // 单线程
QueuedConnection, // 多线程异步
BlockingQueuedConnection, // 多线程同步
UniqueConnection = 0x80 // 唯一连接,用来防止重复连接
};
2.元对象系统
元对象系统分为三大类:QObject类、Q_OBJECT宏和元对象编译器moc
Qt的类包含Q_OBJECT宏 moc编译器会对该类编译成标准的C++代码
3.事件模型
1.事件的创建
鼠标事件,键盘事件,窗口调整事件,模拟事件
2.事件的交付
Qt通过调用虚函数QObject::event()来交付事件。
3.事件循环模型
主事件循环通过调用QCoreApplication::exec()启动,
随着QCoreApplication::exit()结束,
4.本地的事件循环可用利用QEventLoop构建。
一般来说,事件是由触发当前的窗口系统产生的,但也可以通过使用 QCoreApplication::sendEvent()和 QCoreApplication::postEvent()来手工产生事件。需要说明的是QCoreApplication::sendEvent()会立即发送事件, QCoreApplication::postEvent()则会将事件放在事件队列中分发。
4.自定义事件