c++ - 从 QWidget 中的 QTextEdit 获取文本

标签 c++ qt qt4

我有一个 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 的句柄。

最佳答案

您需要手动跟踪您的文本编辑。通过在父小部件中存储指向它们的指针,或者您可以使用查找表,例如一个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。

关于c++ - 从 QWidget 中的 QTextEdit 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14835174/

相关文章:

c++ - 有没有办法在模板类中处理可变数量的参数?

C# : catch all errors/exceptions of a mixed managed/unmanaged process

python没有获取环境变量,但它是在mac os上设置的

linux - 我应该如何在 Qt 中编写窗口管理器?

c++ - 当 QMenu 的 QAction 之一未触发时,防止 QMenu 关闭

C++ 运算符重载不符合数学要求

c++ - std::tuple 成员指针行为

c++ - 使用 Qt 在 VS2015 中构建的程序的发布版本运行然后关闭而没有错误?

c++ - 从 QT 中的自定义小部件插件公开子控件

c++ - 如何将静态常量变量保留为类的成员