网站建设及 维护合同,什么是软件开发工程师,昆明市住房和城乡建设局官方网站,学校网站建设方面汇报信号槽中的函数重载 QT4的方式QT5的方式函数指针重载函数QT5信号函数重载解决方案 总结 QT4的方式
Qt4中声明槽函数必须要使用 slots 关键字, 不能省略。
信号函数#xff1a; 槽函数#xff1a; mainwondow: cpp文件#xff1a;
#include mainwindow.h… 信号槽中的函数重载 QT4的方式QT5的方式函数指针重载函数QT5信号函数重载解决方案 总结 QT4的方式
Qt4中声明槽函数必须要使用 slots 关键字, 不能省略。
信号函数 槽函数 mainwondow: cpp文件
#include mainwindow.h
#include ui_mainwindow.h
#include QDebugMainWindow::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);
}
调用有参的信号函数 调用无参的信号函数 QT5的方式
函数指针重载函数 QT5信号函数重载
信号函数和槽函数和之前QT4中是一样的。 信号函数 槽函数 关联方式
报错如下E:\Code\Qt\mySignalAndSlot3\mainwindow.cpp:20: error: no matching function for call to MainWindow::connect(me*, unresolved overloaded function type, myteacher*, unresolved overloaded function type) connect(tom,me::sendMsg,teacher,myteacher::receiveMsg); ^
信号和槽都是通过函数名去关联函数的地址, 但是这个同名函数对应两块不同的地址, 一个带参, 一个不带参, 因此编译器就不知道去关联哪块地址了, 所以如果我们在这种时候通过以上方式进行信号槽连接, 编译器就会报错。
解决方案
可以通过定义函数指针的方式指定出函数的具体参数这样就可以确定函数的具体地址了。 定义函数指针指向重载的某个信号或者槽函数在connect函数中将函数指针名字作为实参就可以了。
#include mainwindow.h
#include ui_mainwindow.h
#include QDebugMainWindow::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);
} 总结
Qt4的信号槽连接方式因为使用了宏函数, 宏函数对用户传递的信号槽不会做错误检测, 容易出bugQt5的信号槽连接方式, 传递的是信号槽函数的地址, 编译器会做错误检测, 减少了bug的产生当信号槽函数被重载之后, Qt4的信号槽连接方式不受影响当信号槽函数被重载之后, Qt5中需要给被重载的信号或者槽定义函数指针