I have a QTabWidget
, where each tab has a QPlainTextEdit
as its widget. So, how do I access each tab widget? How do I edit that widget?
Asked
Active
Viewed 2.1k times
8

Daniel Hedberg
- 5,677
- 4
- 36
- 61

Kazuma
- 1,371
- 6
- 19
- 33
1 Answers
13
You can use the widget
function of QTabWidget
in order to get the widget at the specified tab index.
If the QPlainTextEdit
is the only widget of every tab page then the returned widget will be that. Otherwise you need to get the children
of the widget and find the QPlainTextEdit
in them.
QPlainTextEdit* pTextEdit = NULL;
QWidget* pWidget= ui->tabWidget->widget(1); // for the second tab
// You can use metaobject to get widget type or qobject_cast
if (pWidget->metaObject()->className() == "QPlainTextEdit")
pTextEdit = (QPlainTextEdit*)pWidget;
else
{
QList<QPlainTextEdit *> allTextEdits = pWidget->findChildren<QPlainTextEdit *>();
if (allTextEdits.count() != 1)
{
qError() << "Error";
return;
}
pTextEdit = allTextEdits[0];
}
// Do whatever you want with it...
ptextEdit->setPlainText("Updated Plain Text Edit);

pnezis
- 12,023
- 2
- 38
- 38
-
4Advice: avoid using `QWidget* pWidget= ui->tabWidget->widget(1);` and instead use `QWidget* pWidget= ui->tabWidget->findChild
("your_tab_object_name");`. This will ensure that even when movable your code will work as intended. The moment you rearrange your tabs (through code or by making them movable) the first piece of code will fail to return the tab you actually want. – rbaleksandar Jul 12 '16 at 10:49 -
Furthermore you should be using `qobject_cast
` and then test the result for nullptr instead of checking the meta object's classname. – Folling Aug 14 '20 at 08:36