QTextEdit. How to select text manually?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 18:15:53
 QTextCursor c = textEdit->textCursor();
 c.setPosition(startPos);
 c.setPosition(endPos, QTextCursor::KeepAnchor);
 textEdit->setTextCursor(c);

This piece of code moves the cursor to the start position of the selection using setPosition, then moves it to the end of the selection, but leaves the selection anchor at the old position by specifying a MoveMode as the second parameter.

The last line sets the selection to be visible inside the edit control, so you should skip it if you just want to do some manipulations with the selected text.

Also, if you don't have the exact positions, movePosition is helpful: you can move the cursor in various ways, such as one word to the right or down one line.

I encountered a similar problem. In Windows 10, there might be a bug of 'drag/move'. We use QT_NO_DRAGANDDROP as a compiler option, which makes text selection in QTextEdit not mork anymore.

Solution:

void QTextEditEx::mouseMoveEvent(QMouseEvent *event)
{
    QTextEdit::mouseMoveEvent(event);
    if (event->buttons() & Qt::LeftButton)
    {
        QTextCursor cursor = textCursor();
        QTextCursor endCursor = cursorForPosition(event->pos()); // key point
        cursor.setPosition(pos, QTextCursor::MoveAnchor);
        cursor.setPosition(endCursor.position(), QTextCursor::KeepAnchor);
        setTextCursor(cursor);
    }
}

void QTextEditEx::mousePressEvent(QMouseEvent *event)
{
    QTextEdit::mousePressEvent(event);
    if (event->buttons() & Qt::LeftButton)
    {
        QTextCursor cursor = cursorForPosition(event->pos());
        // int pos; member variable
        pos = cursor.position();
        cursor.clearSelection();
        setTextCursor(cursor);
    }
}

reference:

  1. Two existing answers

  2. QTextEdit: get word under the mouse pointer?

Try to use:

QTextCursor cur = tw->textCursor();
cur.clearSelection();
tw->setTextCursor(cur);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!