Gromit
Gromit

Reputation: 61

Creating object in loop dynamically

I want to create many buttons in Qt within a loop.

In header file:

QVector<QPushButton> *btns;

In cpp file:

btns = new QVector<QPushButton>();
for(int i = 0; i <= 10; i++) {
    btns->append(new QPushButton(QString::number(i),this));
}

I'm getting the error:

cannot convert argument 1 from 'QPushButton *' to 'const QPushButton &'

It's probably not hard to fix it, but I am not too good with pointers. Can you help me?

Upvotes: 1

Views: 1249

Answers (2)

You're trying to store the buttons by value. This is not yet possible in Qt containers, since they require the values to by copyable, and no Qt class deriving from QObject is copyable. The QPushButton can't be copied, and can't be stored by value in a Qt container.

What you need to do instead is either:

  1. Store the widgets by pointer:

    class MyClass : ... {
      QList<QPushButton *> m_buttons; // performs the same as QVector, has <<
      ...
    };
    
    for(int i = 0; i <= 10; i++) {
        m_buttons << new QPushButton(QString::number(i),this));
        // you'll be likely adding the buttons to a layout:
        layout().addWidget(m_buttons.back());
    }
    
  2. or, store the widgets by value in a container that doesn't need to copy them:

    // C++11
    class MyClass : ... {
      std::list<QPushButton> m_buttons;
      ...
    };
    
    for(int i = 0; i <= 10; i++) {
        m_buttons.emplace_back(QString::number(i),this));
        // you'll be likely adding the buttons to a layout:
        layout().addWidget(&m_buttons.back());
    }
    

Upvotes: 4

evilruff
evilruff

Reputation: 4085

in the header

QVector<QPushButton*>  btns;

in the source

for(int i = 0; i <= 10; i++) {
   btns.append(new QPushButton(QString::number(i),this));
}

Upvotes: 4

Related Questions