1

我有一个QTabWidget“tw”,我在其中添加了这样的标签:

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);

如何QTextEdit从前景中的选项卡中获取文本(例如,当我单击按钮时,我想将文本从可见选项卡复制到剪贴板或类似的 smtg)。我不知道如何获得QTextEdit.

4

1 回答 1

2

您需要手动跟踪您的文本编辑。通过将指向它们的指针存储在父小部件中,或者您可以使用查找表,例如QHash

假设您有一个MyClass包含您在问题中发布的代码的类:

像这样添加一个成员变量:

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;
};

此变量可以存储(和查找)标签页索引 (0, 1, 2, ...) 中的文本编辑。

你可以做一个这样的添加功能:

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 );
}

然后检索这样的指针QTextEdit

QTextEdit* textEdit = _textEditPerTabPage.value( tabWidget->currentIndex() );

这段代码有一些限制,例如,您必须始终确保使用自己的MyClass::addTab函数并且不要访问QTabWidget::addTab该函数之外的内容。此外,如果您调用QTabWidget::removeTab,您QHash可能不再指向正确的 QTextEdits。

于 2013-02-12T15:19:19.017 回答