Reestablishing expected behavior of cursor in QTextEdit following a dropEvent

47 Views Asked by At

I wrote a class CustomTextEdit inheriting from qTextEdit and overriding the following two methods:

  • bool canInsertFromMimeData(const QMimeData *source) const override;
  • void dropEvent(QDropEvent *e) override;

so that it is possible to use the widget as the destination of a drag-and-drop action.

This has unexpected consequences on the behavior of the text cursor in this widget.

Before any dropEvent, it is possible to visually see where the text cursor is placed. The text cursor position moves to the last place where the mouse has been clicked. This is the expected behavior of the cursor.

Following the execution of the dropEvent, the vertical bar rendering of the text cursor remains positioned after the inserted text. The text cursor no longer moves to the position of the last click in the QTextEdit area.

If other dropEvents are executed, several vertical bars may end up being displayed.

What is the correct procedure to reestablish the default behavior of the text cursor after execution of a dropEvent?

Even the following definition of the dropEvent method produces this strange behavior:

void CustomTextEdit::dropEvent(QDropEvent *e)
{
    this->insertPlainText(QString("<<dropped text>>"));
}
1

There are 1 best solutions below

0
dde On

The solution has been to explicitly set the text cursor before inserting the text, and to call the dropEvent method on the parent class QTextEdit.

void CustomTextEdit::dropEvent(QDropEvent *e)
{
    // setting the text cursor
    QTextCursor cursor = this->textCursor();
    cursor.setPosition(cursorForPosition(e->pos()).position());
    this->setTextCursor(cursor);
    // dropping the text
    this->insertPlainText(QString("<<dropped text>>"));
    // conclude the call by calling the parent method
    QTextEdit::dropEvent(e);
}