Bhavyanshu
Bhavyanshu

Reputation: 536

Programmatically creating a new QTextEdit inside a new tab

I have a tabwidget with QTextEdit having object name as "text_field" (Set through Qt Designer). It is inside one tab. Like for example, in a text editor, files are opened up in multiple tabs. I want to replicate this. So whenever I press "New File" button, it should programmatically create another tab with a new QTextEdit field. Also all the functions I have written so far are using the above mentioned object name, like

void MainWindow::some_function() {
    ...
    ui->text_field->textCursor();
    ...
}

As you can see, I have approached this in a wrong way. The problem is that how am I going to set the same object name for newly created QTextEdit when I press the "New File" button?

I tried something like this.

void MainWindow::on_actionNew_triggered()
{
    QTextEdit *text_field = new QTextEdit();
    ui->tabWidget->addTab(text_field,"Untitled.txt");
    ui->tabWidget->setCurrentWidget(text_field);
}

Result is that it is creating new tab, also adding a QTextEdit widget but the functions are only working for the originally created QTextEdit and not the one that is programmatically created.

Upvotes: 1

Views: 931

Answers (1)

Jablonski
Jablonski

Reputation: 18504

All your textEdits stored in tabWidget, so you can easily access this widgets everywhere, just pass index of needed widget and you will be able do all what you need.

Example how to use.

for(int i = 0; i< ui->tabWidget->count(); i++ )
{
    qDebug() << ui->tabWidget->widget(i);
    QTextEdit* edit = qobject_cast<QTextEdit*>(ui->tabWidget->widget(i));
    if(edit)
        edit->setText("new");
}

In your example:

void MainWindow::some_function() {
    ...
    ui->text_field->textCursor();
    ...
}

you work with only widget which was created in Qt Designer, with my example using only index or just currentIndex() or currentWidhet() methods you can work with these. textEdits.

The main idea is that user can add many widgets and you can't predict how many user wants, but tabWidget store all widgets, so use it!

Upvotes: 1

Related Questions