Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

New QTextBlockFormat from QTextDocument 's StyleSheet



  • Hi,
    If I specify mydoc.setStyleSheet(some css), and I create a new QTextBlocFormat the formatting of the new blockFormat is not the one specified in stylesheet.
    How can I do it ?
    Thanks
    Jimmy



  • @Jim-Gir
    I'm lost. There is no QTextDocument::setStyleSheet(). QTextDocument is not a QWidget. There is a QTextDocument::setDefaultStyleSheet(), but that is not what you say you are using. So how do you get your code to compile/run with mydoc.setStyleSheet()?



  • oh sorry, I meant setDefaultStyleSheet(). And that's my problem. this should set a default style but creating new QTextBlocFormat doesn't seet style like in my custom css.



  • Here is a snippet (it's python I don't think it changes anything)

    from PySide2.QtGui import QTextDocument, QTextCursor, QTextBlockFormat, QTextCharFormat, QBrush, QColor
    
    a = QTextDocument()
    a.setDefaultStyleSheet("""h2 {margin-top: 20px;}""")
    a.setHtml("")
    
    bf = QTextBlockFormat()
    bf.setHeadingLevel(2)
    
    print(bf.topMargin())
    # 0.0
    
    c = QTextCursor(a)
    c.insertBlock(bf)
    
    print(a.toHtml())
    # <body style=" font-family:''; font-weight:400; font-style:normal;">
    # <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p>
    # <h2 style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></h2></body></html>
    

    in this example h2 margin-top is never set as I expect



  • @Jim-Gir
    Test out using

    for example using setHtml() or QTextCursor::insertHtml().

    and see whether these do work? https://doc.qt.io/qt-5/qtextdocument.html#defaultStyleSheet-prop only states these work.



  • Ok I see. inserthtml was my first try before using insertblock. But using It I can't add new block.

    a = QTextDocument()
    a.setDefaultStyleSheet("""h2 {margin-top: 20px;} p {margin-top: 15px;}""")
    a.setHtml("""<p>bbb</p>""")
    
    c = QTextCursor(a)
    c.movePosition(QTextCursor.End)
    c.insertHtml("<h2>bla</h2>")
    print(a.toHtml())
    
    #<html><head><meta name="qrichtext" content="1" /><style type="text/css">
    #p, li { white-space: pre-wrap; }
    #</style></head><body style=" font-family:''; font-weight:400; font-style:normal;">
    #<p style=" margin-top:15px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">bbb<span style=" font-size:x-large; font-weight:600;">bla</span></p></body></html>
    

Log in to reply