linuxqtqtextedittext-coloring

Can I retrieve the text color (or background color) of the character at the text cursor from QTextEdit?


I have a QTextEdit window with words and letters displayed in several colors. I want to be able to retrieve the color of each part of the text when processing the contents of the window. My attempt so far has been to save the entire contents as an html file and then parse through that to extract only the text with the color information. This is very cumbersome and difficult. I would much prefer to process the text using the QTextCursor if I could retrieve the color of the text at the cursor position. I have searched for the appropriate function but have not found one.

Is there a function to retrieve the color (or the format) at the QTextCursor position?

Or alternatively is there a way to retrieve each contiguous section of words and/or characters that have the same color (or format) with the format information?


Solution

  • Well I have found a way to do what I wanted. Here is the relevant code:

    QTextCursor tc = qte->textCursor();
    tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
    while(tc.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor))
    {
        QTextCharFormat tcf = tc.charFormat();
        int bg = tcf.background().color().rgb();
        int fg = tcf.foreground().color().rgb();
        printf("bg=%x fg=%x\n", bg, fg);
    }
    

    any comments or improvements are welcome.

    [Corrected above]: I originally had

    QColor bg = tcf.background().color().rgb();
    QColor fg = tcf.foreground().color().rgb();
    

    but with .rgb() on the end, it converts QColor to int.