0

I am trying to concatenate my copy message and the previous message. In other words, I want to paste new string wherever user wants in QTextEdit. I could insert it at the end of the string.
Here is my code:

void MessageDialog::pasteMessage()
{
    QClipboard *clipboard = QApplication::clipboard();
    QString previousMessage = m_messageEdit->toPlainText();
    m_messageEdit->setText(previousMessage+clipboard->text());
}

It just pastes at the end of string.

I've also read it and I've tried like this:

void MessageDialog::pasteMessage()
{
    QClipboard *clipboard = QApplication::clipboard();
    QTextCursor cursor(m_messageEdit->textCursor());
    m_messageEdit->moveCursor (QTextCursor::End);
    m_messageEdit->insertPlainText (clipboard->text());
    m_messageEdit->setTextCursor (cursor);
}

Actually it pastes it in a new line, which is not what I want.

Any suggestion?

Community
  • 1
  • 1
Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
  • 2
    `QTextEdit::insertplainText()` takes a QString as an arg. Change to `m_messageEdit->insertPlainText (clipboard->text());` – techneaz Jul 21 '15 at 10:17

2 Answers2

1

If you can access directly to QTextEdit object, then QTextEdit::paste() is what you need. It retrieves text from clipboard and tries to paste it into the current cursor position. Here is a small example.

#include <QApplication>

#include <QMessageBox>

#include <QTextEdit>
#include <QShortcut>

int main( int argc, char ** argv )
{
    QApplication app( argc, argv );

    // create multiline edit
    QTextEdit edit;
    edit.setFixedSize( 200, 100 );

    // create shortcut (different from Ctrl+V)
    QShortcut shortcut( Qt::Key_F4, &edit );

    // connect shortcut signal with text edit slot
    QObject::connect( &shortcut,  &QShortcut::activated,
                      &edit,      &QTextEdit::paste );

    // show edit
    edit.show( );

    app.exec( );

    return 0;
}

If you want to paste something from clipboard, you just need to press F4.

John Smith
  • 109
  • 1
  • 7
0

try it :

void MessageDialog::pasteMessage()
{
    QString messageText = m_messageEdit->toPlainText();
    int msg_lng = messageText.length();
    QClipboard *clipboard = QApplication::clipboard();
    int currentPos = m_messageEdit->textCursor().position();
    int r_currentPos = msg_lng - currentPos;
    QString subMessage_one = messageText.left(currentPos);
    QString subMessage_two = messageText.right(r_currentPos);
    m_messageEdit->setText(subMessage_one+clipboard->text()+subMessage_two);
    m_messageEdit->moveCursor (QTextCursor::End);
}
Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81