三个顾客 Anderson、Bruce、Castiel 都要订饭,分别对应三个按钮,点击一个按钮,就会弹出给该顾客送饭的消息。注意这个例子只使用一个槽函数,而三个顾客名称是不一样的,弹窗时显示的消息不一样,这需要一些 技巧,下面我们开始这个示例的学习。
编辑好界面之后保存。这样三个信号的源头就设置好了,下面需要编写接收它们信号的槽函数。我们回到 QtCreator 的代码编辑模式,打开头文件 widget.h,向类里添加槽函数声明:
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>namespace Ui {
class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();public slots: //添加槽函数进行弹窗void FoodIsComing();private:Ui::Widget *ui;
};#endif // WIDGET_H
FoodIsComing 就是我们需要添加的槽函数,添加好声明之后,下面再向 widget.cpp 添加代码:
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDebug>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);//三个按钮的信号都关联到 FoodIsComing 槽函数connect(ui->pushButtonAnderson, SIGNAL(clicked()), this, SLOT(FoodIsComing()));connect(ui->pushButtonBruce, SIGNAL(clicked()), this, SLOT(FoodIsComing()));connect(ui->pushButtonCastiel, SIGNAL(clicked()), this, SLOT(FoodIsComing()));
}Widget::~Widget()
{delete ui;
}void Widget::FoodIsComing()
{//获取信号源头对象的名称QString strObjectSrc = this->sender()->objectName();qDebug()<<strObjectSrc; //打印源头对象名称//将要显示的消息QString strMsg;//判断是哪个按钮发的信号if( "pushButtonAnderson" == strObjectSrc ){strMsg = tr("Hello Anderson! Your food is coming!");}else if( "pushButtonBruce" == strObjectSrc ){strMsg = tr("Hello Bruce! Your food is coming!");}else if( "pushButtonCastiel" == strObjectSrc ){strMsg = tr("Hello Castiel! Your food is coming!");}else{//do nothingreturn;}//显示送餐消息QMessageBox::information(this, tr("Food"), strMsg);
}