Access To QWidget declared in addTab() function.
-
Hello guys,
I'm trying to create a simple notepad with tabs but I have a problem.
I made a button to create a new Tab and put this code:ui->tabWidget->addTab(new QTextEdit(), QString("Tab " + QString::number(ui->tabWidget->count() + 1)));
My question is, there is a way yo access the QTextEdit I declared in the addTab() function?
-
Hi,
QTabWidget::widget is one way.
-
Hi
Do note that QTabWidget::widget returns the QTextEdit as a QWidget pointer so you need to use
qobject_cast to make it a QTextEdit pointer and hence be able to use QTextEdit methods. -
@HenkCoder
Hi np. its likeQTextEdit * edit = qobject_cast <QTextEdit*> ( ui->tabWidget->widget(0)) ; if (edit) { // check is important as if its not a QTextEdit then edit is null and app crash :) edit->xxxxx(); }
-
More information in the function documentation.
-
Hi
Hey, what does that It statement do? And what do I have to write instead of xxxxx()?
Hi. this statement takes a base pointer (QWidget *) and cast it to the concrete child type.
In this case a QTextEdit.
This only works it IS a QTextEdit there.
So basically we do likeSomeClass * ptr = ( Otherclass *) ui->tabWidget->widget(0)
but in a saer manner that will fial its its not a QTextWidget.
A pure cast /old type cast will always work but crash the app if
it really not is a TextEditedit->xxxxx(); is just to show to call functions in it. xxxx is just like any function it has.
like
edit->toPlainText():to get all text into QString or what ever you want to do with your textedit
-
@HenkCoder
Hi
Why would you need it as a global ?If you plan something like NotePad++ with tabs then each tab will be its own QTextEdit
and you need to take the right one, depending on which tab user clicks.So you should hook up a slot to the signal
https://doc.qt.io/qt-5/qtabwidget.html#currentChanged
and there you got the index (the parameter) to use to ask for the widget, then
convert it and you can alter text or what you want. -
Hi
You still dont need a global variable for that :)Any button that must access the TextEdit can just get it.
like you cna make a helper function to make this easy
TextEdit * MainWindow::GetEditor() { return q_objectcast<TextEdit *> ( ui->tabWidget->currentWidget() ); } then in BOLd button clicked etc , you can do void BoldClicked() { TextEdit * edit = GetEditor(); to have access to the current tab as a TextEdit if (edit) { make text bold ... } }