How to get calling button from a clicked event

11k views Asked by At

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

2

There are 2 answers

0
Piotr Dobrogost On BEST ANSWER

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.

0
DigviJay Patil On
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!