[Interest] QTextDocument and Undo

Igor Mironchik igor.mironchik at gmail.com
Fri Jul 1 09:34:14 CEST 2016


Hi.

On 01.07.2016 10:17, Rainer Wiesenfarth wrote:
> 2016-07-01 9:01 GMT+02:00 Igor Mironchik <igor.mironchik at gmail.com>:
>> What if I create Text, then change text in it, then make two undo commands?!
>> It undo changing text and creation of Text item. Ok. But...
>>
>> Then I want to redo this two commands. I redo "create", so Text item now is
>> created again, then I redo "text change" that implemented with
>> QGraphicsTextItem::document()->redo(). But...
>>
>> But Text item with its QTextDocument was created again so QTextDocument's
>> undo stack is empty. I.e. redo() does nothing.
> I am not sure if this will work (it has been some time since I used
> undo/redo), but can't you keep the created text item, including it's
> undo stack until the text-item-create-command is _deleted_ (not only
> undone)? Or is this approach what you mean by "Implement your own undo
> commands for text interactions in Text item?"

I never call QUndoStack::clear().

But I found simple solution:

UndoChangeTextOnForm::UndoChangeTextOnForm( Form * form, const QString & 
id )
     :    QUndoCommand( QObject::tr( "Change Text" ) )
     ,    m_form( form )
     ,    m_id( id )
     ,    m_undone( false )
     ,    m_doc( 0 )
{
}

UndoChangeTextOnForm::~UndoChangeTextOnForm()
{
     if( !m_doc.isNull() )
         m_doc->deleteLater();
}

void
UndoChangeTextOnForm::undo()
{
     m_undone = true;

     FormText * text = dynamic_cast< FormText* > (
         m_form->findItem( m_id ) );

     if( text )
     {
         m_doc = text->document();

         m_doc->setParent( Q_NULLPTR );

         text->document()->undo();
     }
}

void
UndoChangeTextOnForm::redo()
{
     if( m_undone )
     {
         FormText * text = dynamic_cast< FormText* > (
             m_form->findItem( m_id ) );

         if( text )
         {
             if( !m_doc.isNull() && m_doc.data() != text->document() )
                 text->setDocument( m_doc.data() );

             text->document()->redo();
         }
     }
}

I just store QTextDocument on undo(). And set it back if it changed, 
i.e. when Text item was deleted and created again.

m_doc is QPointer< QTextDocument >...

It works. But my undo stack always grows.



More information about the Interest mailing list