1

I am making a class that is a QWidget descendant and which consists of buttons (a button table). Now, signal that is sent by this object is straightforward: void wasClicked(size_t x, size_t y) which sends button coords in the grid. But for this, I need to connect QPushButton's click signal to my widget. Since number of slots/signals depends on grid size, which is not determined at runtime, i can't create enough slots in advance. What should I do then?

RomaValcer
  • 2,786
  • 4
  • 19
  • 29

1 Answers1

3

I would connect the buttons so that they all send a signal to the same slot.

I did not test this code. It is just an attempt for a proof of concept

class ButtonTable : public QWidget 
{    
    Q_OBJECT       

public:
    ButtonTable()
    void createButtons();


private:
    int height;
    int width;
    QVector<Button*> buttons

private slots:
   btnClicked();
};

void ButtonTable::createButtons() {
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; j++) {
            Button* btn = new Button(this);
            btn.row = i;
            btn.col = j;
            connect(button, SIGNAL(clicked()), this, SLOT(btnClicked()));
            buttons.push_back(btn);
        }
    } 
}


void ButtonTable::btnClicked()
{
   Button *btn = qobject_cast<Button *>(sender());  
   //Do something with button

}


class Button : public QToolButton
{
    Q_OBJECT

public:
    explicit Button(QWidget *parent = 0);
    int row;
    int col;
};

So there are many buttons but each clicked() button goes to one single slot. You can find out what button was pressed with QObject::sender(), and because they are custom buttons that inherit from QToolButton, you can store extra information you need inside that class.

Keep in mind you will also have to do the layout of the buttons programmatically because of the dynamic size.

Dillydill123
  • 693
  • 7
  • 22