How to get calling button from a clicked event

10,480

Solution 1

Connect each button's click() signal with one and the same slot and use QObject * QObject::sender () const [protected] in this slot to find out which button sent the signal (was clicked). Alternatively you could use QSignalMapper which is a special class made just for this kind of task.

Solution 2

QPushButton *buttonA = new QPushButton("A");
QPushButton *buttonB = new QPushButton("B");
QPushButton *buttonC = new QPushButton("C");

buttonA->setObjectName("A");
buttonB->setObjectName("B");
buttonC->setObjectName("C");

connect(buttonA, SIGNAL(clicked()), this, SLOT(testSlot()));
connect(buttonB, SIGNAL(clicked()), this, SLOT(testSlot()));
connect(buttonC, SIGNAL(clicked()), this, SLOT(testSlot()));

//Now in slot implementation
void QWidget::testSlot()
{
  QObject *senderObj = sender(); // This will give Sender object
  // This will give obejct name for above it will give "A", "B", "C"
  QString senderObjName = senderObj->objectName(); 

  if(senderObjName == "A")
  {
   //Implement Button A Specific 
  }
  //Similarly for "B" and "C"
  if(senderObjName == "B")
  {
   //Implement Button B Specific 
  }
  if(senderObjName == "C")
  {
   //Implement Button C Specific 
  }
}

I have used this method to implement such case because code is more readable but it may be time consuming as String comparison comes. Thank you!

Share:
10,480
Buzzzz
Author by

Buzzzz

Standard computer nerd..

Updated on July 17, 2022

Comments

  • Buzzzz
    Buzzzz almost 2 years

    I'm trying to make an small gui to deploy .ear and .war files on my local glassfish installation. SO i have made five rows containing a file name field, a checkbox and a button to bring up a file dialogbox to locate the war/ear file. It would be nice to have all buttons call the same function and from the function sort out which of the five buttons who made the call ( to update the correct text fields ). Don't know if this is the intended way of doing it in an object oriented way but my only gui programming experience is some old win16 event loops :).

    //BRG Anders Olme