0

I have this class in button.h:

class Buttons : public QObject
{
    Q_OBJECT
public:
    Buttons();
    QVector<QPushButton*> buttons;
public slots:
    void getBtnInfo();
};

and in mainwindow.cpp, I connect like this:

Buttons mButtons;
for(int i = 0; i < mButtons.buttons.size(); i++) {
    mButtons.buttons[i] = new QPushButton(mCentralWidget);
    ...
    connect(mButtons.buttons[i], SIGNAL(clicked(bool)), &mButtons, SLOT(getBtnInfo()));
}

It runs without any errors; but the getBtnInfo() slot seems like not do anything. Because I tried simply just debug in this slot, not working.

But if I declare getBtnInfo() slot in mainwindow.h and connect like this:

connect(mButtons.buttons[i], SIGNAL(clicked(bool)), this, SLOT(getBtnInfo()));

then it works.
I wonder why? And how do I solve the problem above?
Thanks.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Theodore Tang
  • 831
  • 2
  • 21
  • 42

1 Answers1

2

If a variable is created in a function it only exists in that function, then it will not be accessible, and that is what I think is happening, I recommend you to make mButtons a member of the class.

*.h

private:
    Buttons mButtons;
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I tried what you recommend, but the problem is still there. I do not think that is the solution. BTW, I created the variable and connect the signals and slots in the same function. So do you know any other way to solve that problem? – Theodore Tang Nov 18 '17 at 15:37
  • @TheodoreTang I have tried to reproduce your project with what you show me and my modifications and it has worked, maybe I have assumed other things, you could share your project please to be able to test it. – eyllanesc Nov 18 '17 at 15:39
  • I found after I make mButtons to my class, I forgot to remove the declaration of mButtons in that function. I removed it and it worked. Thanks – Theodore Tang Nov 18 '17 at 15:46