Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the currently visible text from a QTextEdit or QPlainTextEdit widget?

Tags:

c++

qt

qtextedit

It seems like this would be a common thing to do, but I can't find how.

I have a QTextEdit or QPlainTextEdit widget with a bunch of text. Enough that scrolling is necessary.

I want another widget to give some information about the currently visible text. To do this, I need to know

  1. when the visible text changes
  2. what's the text?

I see that QPlainTextEdit has the method firstVisibleBlock, but it's protected. This tells me that it's not really something I should be using in my application. I wouldn't otherwise need to subclass from the edit window.

I also see that there's the signal updateRequest but it's not clear what I do with the QRect.

How do I do it or where do I find a hint?

like image 248
mmccoo Avatar asked Nov 15 '22 04:11

mmccoo


1 Answers

I've written a minimal program that as two QTextEdit fields. In the left field you write and the text you are writing is shown in the second text edit too. You get the text of a QTextEdit by using toPlainText() and the signal is textChanged().

I've tested it and what you write in m_pEdit_0 is shown in "real-time" in m_pEdit_1.

main_window.hpp

#ifndef __MAIN_WINDOW_H__
#define __MAIN_WINDOW_H__

#include <QtGui/QtGui>
#include <QtGui/QMainWindow>
#include <QtGui/QApplication>

class main_window : public QMainWindow
{
    Q_OBJECT

public:
    main_window( QWidget* pParent = 0 );
    ~main_window();

public Q_SLOTS:
    void on_edit_0_text_changed();

private:
    QHBoxLayout* m_pLayout;
    QTextEdit* m_pEdit_0;
    QTextEdit* m_pEdit_1;
};

#endif // !__MAIN_WINDOW_H__

main_window.cpp

#include "main_window.hpp"

main_window::main_window( QWidget *pParent ) : QMainWindow( pParent )
{
    m_pEdit_0 = new QTextEdit( this );
    m_pEdit_1 = new QTextEdit( this );

    connect( m_pEdit_0, SIGNAL( textChanged() ), this, SLOT( on_edit_0_text_changed() ) );

    m_pLayout = new QHBoxLayout;
    m_pLayout->addWidget( m_pEdit_0 );
    m_pLayout->addWidget( m_pEdit_1 );

    QWidget* central_widget = new QWidget( this );
    central_widget->setLayout( m_pLayout );

    setCentralWidget( central_widget );
}

main_window::~main_window()
{
}

void main_window::on_edit_0_text_changed()
{
    m_pEdit_1->setText( m_pEdit_0->toPlainText() );
}

main.cpp

#include "main_window.hpp"

int main( int argc, char* argv[] )
{
    QApplication a(argc, argv);

    main_window mw;
    mw.show();

    return a.exec();
}

Edit:

This would work too, but would lack in performance for huge documents:

void main_window::on_edit_0_text_changed()
{
    QStringList text_in_lines = m_pEdit_0->toPlainText().split( "\n" );

    m_pEdit_1->clear();

    for( int i = 0; i < text_in_lines.count(); i++ )
    {
        m_pEdit_1->append( text_in_lines.at( i ) );
    }
}
like image 183
Exa Avatar answered Dec 28 '22 07:12

Exa