I found that implementing this is possible using QTextEdit / QTextDocument. The simplest implementation that I can think of is presented in this answer for the reference of the future seeker.
Please note that saving / loading must be configured as regular .toHtml (), without saving the necessary information.
Inserting code is very simple:
QTextFrame * frame; frame = cursor.insertFrame( code_block_format_ ); connect( frame, SIGNAL( destroyed() ), this, SLOT( codeBlockDeleted() ) ); code_blocks_.append( frame );
pay attention to two variables that you can save in the class:
QTextFrameFormat code_block_format_; QList<const QTextFrame*> code_blocks_;
We need a format so that it is consistent and distinctive. Its mat is initialized in the constructor like this:
code_block_format_.setBackground( QBrush( Qt::yellow ) ); code_block_format_.setBorder( 1 ); code_block_format_.setBorderStyle( QTextFrameFormat::BorderStyle_Inset); code_block_format_.setMargin( 10 ); code_block_format_.setPadding( 4 );
We need a list so that we can determine if a particular frame is coded or not. Since all objects that inherit from QTextObject must be created by QTextDocument :: createObject (), we cannot simply subclass QTextFrame (in fact, I think we can, but are not sure yet).
Now the separation of the contents of the code from the rest can be performed in the usual way:
for ( it = frame->begin(); !(it.atEnd()); ++it ) { child_frame = it.currentFrame(); child_block = it.currentBlock(); if ( child_frame != NULL ) { if ( code_blocks_.contains( frame ) ) { } } }
but note that this is simplified for brevity. It is necessary to consider the nested frames.
If you are interested in a full implementation, check out the git repository (work continues, November 2012).