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?
Asked
Active
Viewed 970 times
1

RomaValcer
- 2,786
- 4
- 19
- 29
-
2Use a single slot and `QObject::sender()` in the slot to figure out what button emitted the signal. http://doc.qt.io/qt-5/qobject.html#sender – drescherjm Jul 29 '16 at 17:15
-
@drescherjm please make this into an answer, and I will gladly accept it. – RomaValcer Jul 29 '16 at 17:19
-
I believe @Dillydill123 answered it pretty well. I would accept that answer. – drescherjm Jul 29 '16 at 17:48
1 Answers
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
-
1You should only ever do this in Qt 4. In Qt 5, such code has no place, and you shouldn't be using `sender()`. – Kuba hasn't forgotten Monica Jul 29 '16 at 22:00
-
-
1http://doc.qt.io/qt-5/qt5-intro.html#new-connection-syntax – Kuba hasn't forgotten Monica Jul 29 '16 at 22:40
-
@KubaOber Thanks, I learn a lot from your answers... Even though I use Qt5 for 1 of the 4 projects I develop at work the other 3 are stuck using Qt4 and will be stuck for years to come so I don't use the new Qt5 connection syntax yet. I will try to keep this in mind when we finally move to Qt5. – drescherjm Jul 30 '16 at 14:13
-
It is not hard to use an adapter object to get Qt 5 syntax in Qt 4 :) – Kuba hasn't forgotten Monica Aug 01 '16 at 13:28