Qt, PushButton, id attribute? Any way to find out which button was pressed

void MainWindow::addRadioToUI() { int button_cunter=4; while(!database.isEmpty()) { button_cunter++; QPushButton *one = new QPushButton("Play: "+name(get_r.getTrackId())); one->setIcon(QIcon(":/images/play_button.png")); one->setMaximumWidth(140); one->setFlat(true); QGroupBox* get_rGB = new QGroupBox("somethink"); QFormLayout* layout = new QFormLayout; if(button_cunter%5 == 0){ layout->addWidget(one); } get_rGB->setLayout(layout); scrollAreaWidgetContents->layout()->addWidget(get_rGB); } } 

I have several QPushButtons that are added automatically. Is there a way to add an id or sth else attribute to a button and then find out which button was clicked? I have different actions for each button.

+6
source share
3 answers

QApplication offers sender() , which contains the object that sent the signal. So you can do:

 //slot, this could also be done in a switch if(button[X] == QApplication::sender()){ doX(); }else if(button[Y] == QApplication::sender()){ doY(); } 

http://doc.qt.io/qt-4.8/qobject.html#sender

+5
source

QSignalMapper pretty good for this type of thing.

You would define your slot, for example:

 public slots: void clicked(int buttonId); // or maybe trackId 

Then add the QSignalMapper* member to your class and connect it to this slot:

  signalMapper = new QSignalMapper(this); connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(clicked(int))); 

In addRadioToUI , after creating your button, do the following:

  signalMapper.setMapping(one, button_cunter); // or trackId if that more practical 

If you only need a pointer to the object that activated the signal, you can use the static function QOjbect::sender in your slot to get a handle to that.

+5
source

Use QButtonGroup. It takes an identifier as a parameter when adding a button and provides an identifier for a slot when a button is pressed in a group.

+2
source

Source: https://habr.com/ru/post/904834/


All Articles