Add custom HTML class property to selected block in QTextEdit

I am not new to Qt, but cannot find how to add a custom css class to the selected block in QTextEdit.

As far as I know, the format is changed with the following code:

QTextCursor cursor = textEdit->textCursor();
QTextBlockFormat bfmt;
// Apply format changes
cursor.setBlockFormat(bfmt);

      

When I do this, the generated HTML creates a range with inline styling in it, but I want to insert a css class:

<SPAN class='myclass'>text</span>

      

I am missing a function inside the QTextBlockFormat to set the CSS class for the text.

+3


source to share


1 answer


You should emulate this behavior by manually adding tags <span style="">

to the selected text:

QString oldText = cursor.selectedText();
// not the best way to concat three strings, but for example only...
cursor.insertHtml(QString("<span class=\"%1\">%2</span>").arg("myclass").arg(oldText));

      



selectedText()

will return the selected text, but insertHtml()

will insert new text at the start of the cursor, deleting the current selection, if any.

0


source







All Articles