2012-02-19 46 views

Trả lời

24
QTextCursor c = textEdit->textCursor(); 
c.setPosition(startPos); 
c.setPosition(endPos, QTextCursor::KeepAnchor); 
textEdit->setTextCursor(c); 

Đoạn mã này di chuyển con trỏ đến vị trí bắt đầu của sự lựa chọn sử dụng setPosition, sau đó di chuyển nó đến cuối của sự lựa chọn, nhưng lá neo lựa chọn ở vị trí cũ bằng cách xác định một MoveMode như thứ hai tham số.

Dòng cuối cùng đặt lựa chọn hiển thị bên trong điều khiển chỉnh sửa, vì vậy bạn nên bỏ qua nếu bạn chỉ muốn thực hiện một số thao tác với văn bản đã chọn.

Ngoài ra, nếu bạn không có vị trí chính xác, movePosition là hữu ích: bạn có thể di chuyển con trỏ trong various ways, chẳng hạn như một từ sang phải hoặc xuống một dòng.

+0

Làm thế nào để cập nhật khu vực lựa chọn? –

-3

Cố gắng sử dụng:

QTextCursor cur = tw->textCursor(); 
cur.clearSelection(); 
tw->setTextCursor(cur); 
0

tôi gặp phải một vấn đề tương tự. Trong Windows 10, có thể có lỗi 'kéo/di chuyển'. Chúng tôi sử dụng QT_NO_DRAGANDDROP làm tùy chọn trình biên dịch, điều này làm cho việc lựa chọn văn bản trong QTextEdit không còn mork nữa.

Giải pháp:

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); 
    } 
} 

tham khảo:

  1. Hai câu trả lời hiện

  2. QTextEdit: get word under the mouse pointer?

Các vấn đề liên quan