Nominate our 2022 Qt Champions!

How to select the highlighted string in QPlaintTextEdit

  • I have a QPlainTextEdit which have highlighted strings is there any way to get this text when I put the cursor on it I try something like

      QTextCursor cur(ui->plainTextEdit_PREVIEW->document());; // to get all the line
      if (!cur.selectedText().isEmpty()) {
      qDebug() << "block = " << cur.selectedText();

    I try also QTextCursor::WordUnderCusor but all not work because may the highlighted string consists of many words is there to so in Qt or i should to code it
    I try to loop through the text left and right the cusor and check if it's background is colored or not and it works I ask if there is a better way to to this

  • @AmrCoder You're using the wrong text cursor. The document and textedit cursor's are different.

    Here is the code you want:

    qDebug() << ui->plainTextEdit->textCursor().selectedText();

    Edit: I may be misunderstanding this... when you say highlighted strings, are you talking about the highlighted SELECTED string, or some other type of highlighting? My code above works on normal highlighted selections but not if you are doing something custom or talking about highlighting in the sense of colorization.

Log in to reply