How to get calling button from a clicked event

Buzzzz picture Buzzzz · Mar 4, 2011 · Viewed 10.3k times · Source

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

Answer

DigviJay Patil picture DigviJay Patil · Sep 9, 2014
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!