Paul Bae
Paul Bae

Reputation: 60

Qt get text changed

Alright, so we have the private slot method textChanged that notifies us when a textEdit object was modified. This implementation is rather robust and informs us when text is inserted with keyboard, with copy and paste, and most of anything else.

Is there anyway, however, to get the actual text that was changed?

Upvotes: 0

Views: 1745

Answers (1)

Jablonski
Jablonski

Reputation: 18524

As Igor said, you can use QTextDocument. Use this code example:

Do connection:

connect( ui->textEdit->document(), SIGNAL(contentsChange(int,int,int)), this, SLOT(change(int,int,int)));

Create slot:

void MainWindow::change(int pos, int del, int add)
{
    QString added = ui->textEdit->toPlainText().mid(pos,add);
    qDebug() << added;
}

In header:

  void change(int, int, int);

And now you can get text which was pasted or typed in QTextEdit

About perfomance. Let's experiment. Write this slot.

void MainWindow::clicked(int pos, int del, int add)
{
    QElapsedTimer tmr;
    tmr.start();
    QString added = ui->textEdit->toPlainText().mid(pos,add);
    qDebug() << added;
    qDebug() << "operation tooks" << tmr.elapsed() <<" ms";
}

Don't forget #include <QElapsedTimer>

Output when I type:

operation tooks 0  ms 
"f" 
operation tooks 0  ms 
"d" 
operation tooks 0  ms 
"g" 
operation tooks 0  ms 
"r" 
operation tooks 0  ms 
"d" 
operation tooks 0  ms 
"s" 
operation tooks 0  ms 
"f" 
operation tooks 0  ms 

Output when I paste text with 7817 characters including spaces:

...long text...
operation tooks 0  ms 

Try it on your computer, I think it is normal efficiency.

Upvotes: 2

Related Questions