Qt4中声明槽函数必须要使用 slots 关键字, 不能省略。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tom = new me(this);
teacher = new myteacher(this);
//connect(ui->pushButtonqt4,&QPushButton::clicked,this,&MainWindow::sendMsg);
//qt4的连接方式
connect(ui->pushButtonqt4,SIGNAL(clicked()),this,SLOT(sendMsg()) );
connect(tom,SIGNAL(sendMsg()),teacher,SLOT(receiveMsg()));
connect(tom,SIGNAL(sendMsg(QString )),teacher,SLOT(receiveMsg(QString )));
//qt5的连接方式
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::sendMsg()
{
qDebug()<<"调用一次";
//tom->sendMsg();
QString s =" hello";
tom->sendMsg(s);
}
信号函数和槽函数和之前QT4中是一样的。
信号函数;
槽函数:
关联方式:
报错如下:E:\Code\Qt\mySignalAndSlot3\mainwindow.cpp:20: error: no matching function for call to 'MainWindow::connect(me*&,
信号和槽都是通过函数名去关联函数的地址, 但是这个同名函数对应两块不同的地址, 一个带参, 一个不带参, 因此编译器就不知道去关联哪块地址了, 所以如果我们在这种时候通过以上方式进行信号槽连接, 编译器就会报错。
可以通过定义函数指针的方式指定出函数的具体参数,这样就可以确定函数的具体地址了。
定义函数指针指向重载的某个信号或者槽函数,在connect()函数中将函数指针名字作为实参就可以了。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tom = new me(this);
teacher = new myteacher(this);
//connect(ui->pushButtonqt4,&QPushButton::clicked,this,&MainWindow::sendMsg);
//qt4的连接方式
// connect(ui->pushButtonqt4,SIGNAL(clicked()),this,SLOT(sendMsg()) );
// connect(tom,SIGNAL(sendMsg()),teacher,SLOT(receiveMsg()));
// connect(tom,SIGNAL(sendMsg(QString )),teacher,SLOT(receiveMsg(QString )));
//qt5的连接方式
//函数指针
void (me::*sendMsg1)() ;
void (me::*sendMsg2)(QString s);
void (myteacher::*receiveMsg1)();
void (myteacher::*receiveMsg2)(QString s);
sendMsg1 = &me::sendMsg;
sendMsg2 = &me::sendMsg;
receiveMsg1 = &myteacher::receiveMsg;
receiveMsg2 = &myteacher::receiveMsg;
connect(ui->pushButtonqt4,&QPushButton::clicked,this,&MainWindow::sendMsg);
//connect(tom,&me::sendMsg,teacher,&myteacher::receiveMsg);
//connect(tom,&me::sendMsg,teacher,&myteacher::receiveMsg);
connect(tom,sendMsg1,teacher,receiveMsg1);
connect(tom,sendMsg2,teacher,receiveMsg2);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::sendMsg()
{
qDebug()<<"调用一次";
tom->sendMsg();
QString s =" hello";
tom->sendMsg(s);
}