How can I replace the copied text from QTextEdit i

2019-07-16 00:19发布

I have a QTextEdit, which contains the text:

It's test.

I want to select this text and copy it to my clipboard using Ctrl+C, but I want to replace "test" with "good" in my clipboard.

I mean: I want to get this in my clipboard after copying original text from QTextEdit:

It's good.

Note: I want to replace clipboard when I have copied text from QTextEdit only, I don't want to replace clipboard when any copy action done.

Thanks.

2条回答
看我几分像从前
2楼-- · 2019-07-16 00:31

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();
}
查看更多
萌系小妹纸
3楼-- · 2019-07-16 00:33

Assuming you have a pointer to a QClipboard called clipboard:

QString data = clipboard->text();

data.replace(QString("test"), QString("good"));

clipboard->setText(data);

This uses the functions QString::replace to modify the text of the clipboard (Accessed from QClipboard::text) and QClipboard::setText to set the new text for the clipboard.

查看更多
登录 后发表回答