Qt connect()的第五种重载[=](){}

进行网络相关编程时,需要使用信号和槽,碰到一个={}作为槽函数的语句,感到非常有意思。

  • 用途:实现函数内部的信号接收
  • 原语句
  connect(tcpSocket, &QTcpSocket::readyRead,
          [=](){
              //从通信套接字中取出内容
              QByteArray array = tcpSocket->readAll();
              qDebug()<<array<<endl;
          }
    );
  • 函数原型
static(qmetaobject-connection.html) QObject::connect(const QObject *sender
  , PointerToMemberFunction signal, Functor functor)

测试的简单例子

  • connection.h
#ifndef CONNECTION_H
#define CONNECTION_H

#include <QObject>
#include<QDebug>
class Connection:public QObject
{
  Q_OBJECT
public:
  Connection();
  void test_emit_signal();

public slots:
  void test_slot();
signals:
  void test_signal();

};

#endif // CONNECTION_H
  • connection.cpp
#include "connection.h"

Connection::Connection()
{
  //connect(this,SIGNAL(test_signal()),this,SLOT(test_slot()));出错
  connect(this,&Connection::test_signal,[=](){
    qDebug()<<"in slot"<<endl;
    //信号需要用指针的形式,而不能用SIGNAL()的形式
  }
  );
  this->test_emit_signal();
}

void Connection::test_slot(){
  qDebug()<<"signal received !"<<endl;
}

void Connection::test_emit_signal(){
  emit test_signal();
}
  • main.c
#include <QCoreApplication>
#include"connection.h"
int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);

  Connection *tmp=new Connection();

  return a.exec();
}
  • 值得注意的是用这种方式处理时,信号需要以指针形式书写

版权声明:本文为qq_25188995原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。