QTextEdit. How to select text manually?

后端 未结 3 665
傲寒
傲寒 2021-01-04 06:20

There are functions like textEdit->textCursor()->selectionStart() and textEdit->textCursor()->selectionEnd(), but there are no function

3条回答
  •  情话喂你
    2021-01-04 06:43

    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 work 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?

提交回复
热议问题