How to have a QTextBrowser to display contents of a QTextEdit?

xpg94 picture xpg94 · Mar 31, 2014 · Viewed 11.1k times · Source

I am trying to connect QTextEdit to QTextBrowser, so the text browser widget outputs what is entered in text edit widget. As a signal I used textChanged(), and as a slot I used setText(QString). And these two don't have same parameters.

If I used QLineEdit instead of QTextEdit, in that case there is textChanged(QString) function which is compatible with the slot,but I need to make it work with QTextEdit. Here is the code:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QWidget * mainWidget=new QWidget(this);
    ui->setupUi(this);
    QTextEdit * mainTextEdit=new QTextEdit();
    QTextBrowser * textDisplay=new QTextBrowser();

    connect(mainTextEdit,SIGNAL( textChanged() ),
            textDisplay,SLOT( setText(QString) ) );

    QHBoxLayout * Alayout=new QHBoxLayout();
    Alayout->addWidget(mainTextEdit);
    Alayout->addWidget(textDisplay);
    mainWidget->setLayout(Alayout);
    setCentralWidget(mainWidget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Answer

vahancho picture vahancho · Mar 31, 2014

I would do it in the following way:

Declare the pointers to the text edit and text browser widgets as member variables in the class,

Create a slot onTextChanged() in MainWindow class that will be called as soon as the text edit is changed and setup the connection as:

connect(mainTextEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged()));

Implement the onTextChanged() slot in the following way:

MainWindow::onTextChanged()
{
    QString text = mainTextEdit->toPlainText();
    textDisplay->setPlainText(text); 
}