【QT】:QT實現一個訊號與多個槽的關聯和實現多個訊號與一個槽的關聯
阿新 • • 發佈:2019-01-24
這個問題很簡單,我們定義一個按鈕就是一個訊號,而相應的事件就是一個槽。
而這裡用到的方法就是connect。
connect的兩個例項如下:
connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(FoodIsComing()));
connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(FoodIsComing()));
connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(FoodIsComing() ));
這個就是多個訊號對應的一個槽。
給出的一個程式碼如下:
#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(FoodIsComing()));
connect(ui->pushButton_3,SIGNAL(clicked()),this ,SLOT(FoodIsComing()));
connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(FoodIsComing()));
connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(FoodIsComing()));
// connect(ui->lineEdit,SIGNAL(textEdited(QString)),this,SLOT(PrintText(QString)));
}
Widget::~Widget()
{
delete ui;
}
void Widget::FoodIsComing(){
QString get = this->sender()->objectName();
qDebug()<<get; //列印源頭物件名稱
QString strMsg;
if("pushButton_3" == get){
strMsg = "hello,welcome ,老王";
}
else if("pushButton_4" == get){
strMsg = "hello,welcome ,老李";
}
else if("pushButton_5" == get){
strMsg = "hello,welcome ,老劉";
}
else{
return ;
}
//顯示送餐訊息
QMessageBox::information(this,tr("food"),strMsg);
}
void Widget::on_pushButton_2_clicked() //我餓了
{
QMessageBox::information(this,tr("餐吃完了"),tr("注意,我吃飽了"));
}
把三個訊號關聯到了一個槽裡面,然後通過槽獲得物件名,然後解析成不同的字元表達出來
通過這句話能夠解析出名字:
QString get = this->sender()->objectName();
輸出結果: