I have a QTextEdit which contains It's test.
I want to select this text and copy it to my clipboard using Ctrl+C, but replace "test" with "good" in clipboard only.
How to replace copied text from QTextEdit in clipboard?
2k Views Asked by alihardan AtThere are 2 best solutions below

It would be better to use Signals/Slots to synchronize what to change in clipboard with what you are actually doing in QTextEdit field to avoid undefined behaviors and accidentally modifying things outside the scope of your task. in order to do that catch a signal
emitted when you highlight this particular QTextEdit field, that signal insures you you can copy the highlighted text QTextEdit::copyAvailable(bool yes)
.. yes
indicates availability of a highlighted text.
Most importantly, make sure you are accessing global clipboard only when you CTRL+C the highlighted text from your QTextEdit field, by attaching to the signal QClipboard::dataChanged
which indicates that you copied the text ... then only modify the text.
To test this code: write your sentence .. highlight it .. use CTRL+C to copy to clipboard and its modified.
Example: class files can look like this:
.h
{
private slots:
void textSelected(bool yes);
void changeTextCopiedToCB();
private:
QClipboard *clipboard;
};
Class .cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this->ui->textEdit, &QTextEdit::copyAvailable, this, &MainWindow::textSelected); // emmited when you select the text
clipboard = QApplication::clipboard();
}
void MainWindow::textSelected(bool yes) // Slot called only when you select text in your field
{
if (yes){
qDebug() << this->ui->textEdit->toPlainText();
connect(clipboard, &QClipboard::dataChanged, this, &MainWindow::changeTextCopiedToCB); // wait tor CTRL+C
}
}
void MainWindow::changeTextCopiedToCB() // Once CTRL+C .. the data in clipboard changes..thats my data
{
QString text = clipboard->text();
text.replace(QString("test"), QString("good"));
clipboard->setText(text);
disconnect(clipboard, &QClipboard::dataChanged, this, &MainWindow::changeTextCopiedToCB); // after copy from this field, leave clipboard alone!
qDebug() << clipboard->text();
}
Assuming you have a pointer to a
QClipboard
calledclipboard
:This uses the functions
QString::replace
to modify the text of the clipboard (Accessed fromQClipboard::text
) andQClipboard::setText
to set the new text for the clipboard.