views:

31

answers:

1

I’ve been working with QGraphicsTextItems. I currently have the laid out in a scene, each depicting a physical page of text. Right now I’m overriding the keyReleaseEvent function to redistribute the text typed across all of the pages. The problem with this is that when I set the text with setPlainText, the cursor moves back to the beginning of the textitem that is set as the focus item for the scene.

As you can imagine, this is problematic when typing, especially on another page instead of the one set to focus, it also makes the keyboard shortcuts for cutting and copying not work at all.

Is there a way to set the text of a QGraphicsTextItem without it resetting the cursor / moving the cursor?

+2  A: 

Hi, for your problem, there's one way I see you could fix it, but I'm not sure it's the best one. Here it is:

You can call textCursor() on your QGraphicsTextItem to get the QTextCursor of your QGraphicsTextItem. With this cursor, you can have his position by calling position(). Then keep this value, update the text and then set the position of the cursor by creating a new QTextCursor, setting his position with setPosition(int pos, MoveMode m = MoveAnchor).

I hope this helps.

EDIT to add example:

// graphicsTextItem is of type QGraphicsTextItem*

QTextCursor cursor = graphicsTextItem->textCursor;
int startPosition = cursor.position();

// Do all you need to update your text.

QTextCursor afterCursor;
afterCursor.setPosition(startPosition);

graphicsTextItem->setTextCursor(&afterCursor);

I have not tested this, I wrote it the way I thought it was going to work.

Live