how to clear a QPlainTextBox within a QTabWidget?
-
Hi all -
I have a QTabWidget with four tabs, each containing a QPlainTextBox. How do I go about erasing the contents of the active tab? I've created a slot:
void Widget::on_pushButtonClear_clicked() { int i; i = ui->tabWidget->currentIndex(); }
...but I can't figure out how to:
- use this index to reference the active tab,
- clear a QPlainTextEdit (thought this would be easy, but didn't see anything in the page).
Thanks for any guidance...
-
Hi,
If the QPlainTextEdit is the widget set on the tab, you can use QTabWidget::currentWidget and qobject_cast to cast the pointer to the correct class and then call clear.
-
Hi
Why not simply remove whole tab instead of "cleaning it"
http://doc.qt.io/qt-5/qtabwidget.html#removeTabui->tabWidget->removeTab ( ui->tabWidget->currentIndex() );
and
ui->plainTextEdit->clear(); -
You don't need it, as I suggested, you can get the widget directly.
-
@mpergand I don't know how to do that, at least not with Designer.
But this seems to work, though I'm not sure it's what SGaist had in mind:
void Widget::on_pushButtonClear_clicked() { QWidget *w ; QPlainTextEdit *qpte; w = ui->tabWidget->currentWidget(); qpte = qobject_cast<QPlainTextEdit *>(w->children().at(0)); qpte->clear(); }
Comments?
-
-
@mzimmers said in how to clear a QPlainTextBox within a QTabWidget?:
void Widget::on_pushButtonClear_clicked() { QWidget *w ; QPlainTextEdit *qpte; w = ui->tabWidget->currentWidget(); qpte = qobject_cast<QPlainTextEdit *>(w->children().at(0)); qpte->clear(); }
because this is bound to fail as soon as the first child is not the targeted widget, or if it does not have children at all, I would suggest the following change:
void Widget::on_pushButtonClear_clicked() { QWidget *w ; QPlainTextEdit *qpte; w = ui->tabWidget->currentWidget(); for(QObject *obj : w->children()){ qpte = qobject_cast<QPlainTextEdit *>(obj); if(qpte) qpte->clear(); }
-
No need to make it so complicated: findChild is what you are looking for.
QWidget *w = ui->tabWidget->currentWidget(); QPlainTextEdit *qpte = w->findChild<QPlainTextEdit *>(); if (qpte) { qpte->clear(); }
Since the content of the widget is known, there's no real need for the if, it's to show good practice if you are doing "widget inspection".