[SOLVED] Forcing font in QTextBrowser without StyleSheet or HTML



  • What I'm trying to do is this:

    1. Clone user-editable QTextBrowser's content into read-only QTextBrowser.
    2. Give the user possibility to change font of read-only browser by using QFontDialog. I'm storing the font as string in database.
      I'm trying to do this like that:

    @
    qTextBrowser_ro->setHtml(qTextBrowser_rw->toHtml());
    qFont->fromString(qString);
    qTextBrowser_2->setFont(*qFont);
    @

    It's not working. I know two ways of forcing font inside QTextBrowser: adding HTML tags or setting StyleSheet. I don't want to do that because I don't really know how to easly convert string returned by QFont::toString() to string accepted by QWidget::setStyleSheet() and I don't want to change the content of QTextBrowser itself (by HTML approach) as font can be changed many times...



  • Solution:
    @
    QTextCursor cursor(browser->textCursor());
    cursor.beginEditBlock();
    cursor.movePosition(QTextCursor::Start);
    cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
    cursor.endEditBlock();
    QTextCharFormat format;
    format.setFont(*qFont);
    cursor.setCharFormat(format);
    @


  • Lifetime Qt Champion

    Hi,

    Out of curiosity, why is qFont a pointer ?



  • bq. Out of curiosity, why is qFont a pointer ?

    Oh, but it doesn't matter. It shouldn't be, there is no need for that.



  • Hi,
    another out of curiosity, why is cursor.beginEditBlock()/cursor.endEditBlock() needed.

    I believe you can do without them. These calls must be placed around the actual editing call(cursor.setCharFormat(format);) to make any difference. If you do not care about Undo of the font change, you can do without them completely.



  • Haha, I'm not "Certified Specialist" like you two, guys. I just solved my problem and it's working so I've posted this solution because I've found that a lot of others had the same problem and it wasn't really solvable through Google.

    I thought startEditBlock/endEditBlock works differently (I won't describe how as it's not true anyway - I just didn't read the docs careful enough). I needed this quick so I didn't really care much about being accurate or efficient, just wanted this to work and shared as soon as it worked. :)



  • No, hard feelings. I just wanted to optimize your finding a bit further. :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.