Markus Klingsiek
Markus Klingsiek

Reputation: 35

Qt - Dynamically create, read from and destroy widgets (QLineEdit)

I have the following situation:

I have QSpinBox where the user of my application can select how many instances of an item he wants to create. In a next step, he has to designate a name for each item. I wanted to solve this problem by dynamically creating a number of QLabels and QLineEdits corresponding to the number the user selected in the SpinBox. So, when the number is rising, I want to add new LineEdits, when the number falls, I want to remove the now obsolete LineEdits.

Well, guess what - this turns out much more difficult than I expected. I've searched the web, but the results were more than disappointing. There seems to be no easy way to dynamically create, maintain (maybe in a list?) and destroy those widgets. Can anybody point me in the right direction how to do this?

Upvotes: 1

Views: 751

Answers (1)

mohabouje
mohabouje

Reputation: 4050

Take a while and check QListWidget, it does what you exactly want for you by using QListWidgetItem.

An little example: this function adds a new element to a QListWidgetwith a defined QWidget as view and return the current index:

QModelIndex MainWindow::addNewItem(QWidget* widget) {
    QListWidgetItem* item = new QListWidgetItem;
    ui->listWidget->addItem(item1);
    ui->listWidget->setItemWidget(item, widget);
    return ui->listWidget->indexFromItem(item);
}

Now, if your user selects X items, you should iterate to create X widgets and you could save all the widgets in a QList:

listWidget.clear();
for (int i=0; i<X; i++) {
    QTextEdit* edit = new QTextEdit();
    const QModelIndex& index = addNetItem(edit);
    qDebug() << "New element: " << index;
    listWidget.append(edit);
    // Handle edit text event
    connect(edit, SIGNAL(textChanged()), this, SLOT(yourCustomHandler()));
}

Now, just show the list with all the edit fields.

Upvotes: 2

Related Questions