Qt: qobject_cast<QAbstractButton*>(sender()) : multiple slots are bound to the same signal

function prototype

template <class T>
inline T qobject_cast(const QObject *object)

Returns T if the passed object is T or a subclass of T, otherwise returns 0. Returns 0 if object is 0.
Class T must inherit directly (or indirectly) from QObject and declare the macro Q_OBJECT.
If T does not declare the macro Q_OBJECT, the return value of the function is undefined


//3个信号绑定同一个槽函数
    connect(ui->pushButton_send1,&QPushButton::clicked,this,&MainWindow::deal_sendclicked);
    connect(ui->pushButton_send2,&QPushButton::clicked,this,&MainWindow::deal_sendclicked);
    connect(ui->radioButton_send,&QPushButton::clicked,this,&MainWindow::deal_sendclicked);

void MainWindow::deal_sendclicked()
{
    
    
 //QAbstractButton  类是按钮widgets的抽象基类。
//qobject_cast<QAbstractButton*>(sender())  返回发送信号的对象指针
  if(qobject_cast<QAbstractButton*>(sender())==ui->pushButton_send1)
  {
    
    
      qDebug()<<"pushButton_send1";
  }
  else if(qobject_cast<QAbstractButton*>(sender())==ui->pushButton_send2)
  {
    
    
      qDebug()<<"pushButton_send2";
  }
  else if(qobject_cast<QAbstractButton*>(sender())==ui->radioButton_send)
  {
    
    
      qDebug()<<"radioButton_send";
  }
}

Both QPushButton and QRadioButton inherit from QAbstractButton

You can also get the pointer object that is currently sending the signal by using coercion

 QPushButton *btn=(QPushButton*)this->sender();
  qDebug()<<btn->text();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324210940&siteId=291194637