How do I create a dynamic variable-length array from lineEdit (s)?

I write a program in c++ in the Qt environment, and created an array consisting of lineEdit(s), the program looks like this:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLineEdit>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
MainWindow::~MainWindow()
{
    delete ui;
}
QLineEdit *myLine[3];

void MainWindow::on_pushButton_clicked()
{
for (int i = 0; i< 3; i++)
    myLine[i] = new QLineEdit();
for (int i = 0; i < 3; i++)
    ui->verticalLayout->addWidget(myLine[i]);
}

But I needed to make a dynamic array of variable length instead of a static one from lineEdit(s), so I tried this:

int n = 10;
QLineEdit *myLine = new QLineEdit[n];

Теперь код выглядит:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLineEdit>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
MainWindow::~MainWindow()
{
    delete ui;
}
int n = 10;
QLineEdit *myLine = new QLineEdit[n];

void MainWindow::on_pushButton_clicked()
{

for (int i = 0; i < 3; i++)
    ui->verticalLayout->addWidget(myLine[i]);
}

But for some reason I get the following error: enter a description of the image here

Please help me, how can I create such a dynamic array with a variable length(I need a dynamic one because as I click on the button, I need you will need to add more and more elements ,how do I do this? why do I have an error?

Author: leocoolguy 0, 2020-05-01

1 answers

Why the error? because the array now stores not pointers to QLineEdit, but actually they themselves (You noticed that before you had to create them, but now you don't?). So, here is this line

ui->verticalLayout->addWidget(myLine[i]);

Rewrite it like this

ui->verticalLayout->addWidget(&myLine[i]);

And it should work.

If you need an array that you can add/remove, then 99% of the time you need QVector (if normal c++, then std::vector).

Let's declare

QVectpr<QLineEdit*> myEdits;

Now add just

QLineEdit* ed = new QLineEdit;
for (int i = 0; i < 100; i++) {
  myEdits.append(ed);
  ui->verticalLayout->addWidget(ed);
}

And in the end, don't forget to properly clean or make the main window a parent.

I would also make the vector itself a private class variable.

 2
Author: KoVadim, 2020-05-01 14:03:21