Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt, PushButton, id attribute? Any way to know which button was clicked

Tags:

c++

attributes

qt

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 a few QPushButtons which are added automaticlly. Is there a way to add "id attribute or sth else" to button and next know which button was clicked? I have different action for each button.

like image 436
aptyp Avatar asked Jan 01 '12 10:01

aptyp


3 Answers

QApplication offers sender() which contains which object 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

like image 116
RedX Avatar answered Nov 15 '22 14:11

RedX


QSignalMapper is pretty good for this type of thing.

You would define your slot like this for instance:

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

Then add a QSignalMapper* member to your class and connect it to that slot:

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

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

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

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

like image 22
Mat Avatar answered Nov 15 '22 14:11

Mat


Use QButtonGroup. It takes id as a parameter when a button is added and provides the id to a slot when a button in the group is pressed.

like image 36
W.K.S Avatar answered Nov 15 '22 13:11

W.K.S