0

I'm creating a simple Text Editor in Qt.
I'm able to edit selected text and make it, for example, bold or underline or both. The problem is when the selected text is partially bold, normal or other. So the only way to make it good is to take the selected text and edit it char by char (if it is already cursive and i want it bold too, the char must be both).

This is part of my code in which i can change selected text into bold:

QFont font;
QTextCursor cursor = ui->textEdit->textCursor();
QTextCharFormat format;

if(cursor.hasSelection()){
    font = cursor.charFormat().font();
    if(!cursor.charFormat().font().bold()){
        font.setBold(true);
        format.setFont(font);
        cursor.setCharFormat(format);
    }
    else{
        font.setBold(false);
        format.setFont(font);
        cursor.setCharFormat(format);
   }
   ui->textEdit->setTextCursor(cursor);

The cursive function is identical. This will not work with text already edit.
Example:

randomtext

Now i want to select part of the text such as: "ndomte" and make it all bold. My result is:
randomtext
What i want is:
randomtext

How can i do it?

1 Answer 1

3

Perhaps you can use QTextCursor::mergeCharFormat(const QTextCharFormat & modifier)? http://doc.qt.io/qt-5/qtextcursor.html#mergeCharFormat

Example:

QTextCharFormat format;
format.setFontWeight(QFont::Bold);
cursor.mergeCharFormat(format);
6
  • The result is the same.
    – Daesos
    Commented Jun 8, 2018 at 14:33
  • @Daesos are you still setting the font? The font will be based on the last selected character (e in this case) which is italic. You then apply that to all selected characters.
    – A.Fagrell
    Commented Jun 8, 2018 at 14:33
  • Yes, i just changed setCharFormat() to mergeCharFormat().
    – Daesos
    Commented Jun 8, 2018 at 15:04
  • Can you comment out the format.setFont() lines and use mergeCharFormat and don't forget to set the font weight.
    – A.Fagrell
    Commented Jun 8, 2018 at 15:09
  • It works i forgot to change the weight. Now what can i do the same with Cursive and Underline?
    – Daesos
    Commented Jun 8, 2018 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.