Reputation: 6326
I have a QTabWidget
'tw' to which I add tabs like this:
QWidget *newTab = new QWidget(tw);
tw->addTab(newTab, "Tab name");
QTextEdit *te = new QTextEdit();
te->setText("Hello world");
QVBoxLayout *vbox = new QVBoxLayout();
vbox->addWidget(te);
newTab->setLayout(vbox);
How can I get the text inside the QTextEdit
from the tab that is in the foreground (like when I click a button I'd like to copy the text from the visible tab to the clipboard or smtg like that). I don't know how to get a handle of the QTextEdit
.
Upvotes: 1
Views: 3669
Reputation: 12600
You need to keep track of your text edits manually. Either through storing a pointer to them in a parent widget, or you could make use of a lookup table, e.g. a QHash:
Assuming you have a class MyClass
which contains the code you posted in your question:
Add a member variable like this:
class QTextEdit; // this is a so-called "Forward Declaration" which saves you an
// #include. Google it if you want to know more ;-)
class MyClass
{
// ...
private:
QHash< int, QTextEdit* > _textEditPerTabPage;
};
This variable makes it possible to store (and find) the text edit from the index (0, 1, 2, ...) of your tab pages.
You could do an add function like this:
void MyClass::addTab( QTabWidget* tabWidget, const QString& tabName, const QString& text )
{
// Create the text edit
QTextEdit* textEdit = new QTextEdit();
textEdit->setText( text );
// Create a layout which contains the text edit
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget( textEdit );
// Create a parent widget for the layout
QWidget* newTab = new QWidget( tabWidget );
newTab->setLayout( layout );
// Add that widget as a new tab
int tabIndex = tabWidget->addTab( newTab, tabName );
// Remember the text edit for the widget
_textEditPerTabPage.insert( tabIndex, textEdit );
}
And then retrieve a pointer on the QTextEdit
like this:
QTextEdit* textEdit = _textEditPerTabPage.value( tabWidget->currentIndex() );
This code has a couple of limitations, e.g. you always have to make sure you use your own MyClass::addTab
function and don't access QTabWidget::addTab
outside of that function. Also if you call QTabWidget::removeTab
, your QHash
may no longer point to the proper QTextEdits.
Upvotes: 2