2014-01-14 86 views
2

使用Qt框架選擇文本段有問題。例如,如果我有這個文件:「沒有時間休息」。我想選擇「ime for r」並從文檔中刪除這段文本,我應該如何使用QTextCursor來做到這一點?這裏是我的代碼:使用QTextCursor選擇一段文本

QTextCursor *cursor = new QTextCursor(ui->plainTextEdit->document()); 
cursor->setPosition(StartPos,QTextCursor::MoveAnchor); 
cursor->setPosition(EndPos,QTextCursor::KeepAnchor); 
cursor->select(QTextCursor::LineUnderCursor); 
cursor->clearSelection(); 

不幸的是,它從文本中刪除整行。我嘗試過使用其他選擇類型,如WordUnderCursor或BlockUnderCursor,但沒有結果。或者也許有更好的方法來做到這一點?提前致謝。

回答

4

有幾個問題在你的代碼:

  1. cursor->select(QTextCursor::LineUnderCursor);行選擇當前整個行。你不想刪除整行,那麼你爲什麼要寫這個?刪除這行代碼。
  2. clearSelection()只是取消選擇一切。改爲使用removeSelectedText()
  3. 請勿使用new創建QTextCursor。這是正確的,但不是必需的。儘可能避免使用指針。 QTextCursor通常按值或引用傳遞。您也可以使用QPlainTextEdit::textCursor獲取編輯光標的副本。

所以,代碼應該看起來像:

QTextCursor cursor = ui->plainTextEdit->textCursor(); 
cursor.setPosition(StartPos, QTextCursor::MoveAnchor); 
cursor.setPosition(EndPos, QTextCursor::KeepAnchor); 
cursor.removeSelectedText(); 
+0

謝謝。這幫助了我很多。我是Qt新手,在這裏學習很多東西。 – Zan

+0

@Laszlo Papp我忘了從測試代碼中刪除這些值。感謝您指出。 –

+0

@PavelStrakhov:好的,謝謝。 1-3)都很好。 :) – lpapp

1

您正在清除選擇而不是基於您的願望的字符。

請閱讀該方法的文檔:

void QTextCursor::clearSelection()

由錨設置爲光標位置清除當前的選擇。

請注意,它確實不是刪除選擇的文本。

你可以看到它只刪除了選擇而不是文本。如果有選擇,其內容被刪除

無效QTextCursor :: removeSelectedText()

;:請使用以下方法來代替否則什麼都不做。

已經討論過的理論,讓我們證明你可以寫什麼:

QTextCursor *cursor = new QTextCursor(ui->plainTextEdit->document()); 
cursor->setPosition(StartPos,QTextCursor::MoveAnchor); 
cursor->setPosition(EndPos,QTextCursor::KeepAnchor); 
// If any, this should be block selection 
cursor->select(QTextCursor::BlockUnderCursor); 
cursor->removeSelectedText(); 
     ^^^^^^^^^^^^^^^^^^ 
+0

THX的小費。 – Zan

+0

@贊:不客氣。 – lpapp

相關問題