Important: Please read the Qt Code of Conduct -

Designate QTextBlock as "Heading 1"

  • I build a QTextDocument by code using QTextCursor, and then export it to file in open document format. So far, so good, I can see my text and formats (font size, etc.).

    However, I'd like to designate a text block as "Heading 1", "Heading 2", etc., so that the user can later on easily create a table of contents from my exported document, in the word processing program of their choice.

    Is that possible, and if so, how?

  • Hi,
    as far as I know QTextBlock has its own int number so it would be possible to add a string of your own and then QTextBlock::blockNumber().
    However there is no QString identifier in the QTextBlock itself that I know of.

  • @artwaw
    Docs on blockNumber: "Note that this function only makes sense in documents without complex objects such as tables or frames."
    Also, it doesn't seem to have a set method, so I guess the number is automatically determined in some way.

  • @Asperamanca It is just zero-based index count of all the blocks in the QTextDocument.

  • Moderators

    QTextBlock derives QTextFormat. QTextFormat can store user properties (see QTextFormat::setProperty())
    You just need to define an enum with your custom property ids for example:

    enum PropertyId {
         Heading1PropertyId = QTextFormat::UserProperty+1000
    textBlock.setProperty(Heading1PropertyId, QVariant::fromValue<bool>(true));
    textBlock.boolProperty(Heading1PropertyId); // convenience getter

Log in to reply