PDA

View Full Version : How to interactively adding text to scene



lni
13th February 2010, 12:07
Hi,

I need to provide a way to add/modify text to scene interactively, just like Windows' Painter program. Are there any sample codes? It seems to be quite complicated...

I can add text using QGraphicsScene::keyPressEvent together with QGraphicsSimpleTextItem, but I would like to make it work exactly the same way as Windows' Painter program....

Help is very appreciated...

psih128
13th February 2010, 13:36
use QGraphicsTextItem

I also add the following code to make it editable:

QVariant MyTextEdit::itemChange(GraphicsItemChange change, const QVariant &value)
{
switch (change) {
case ItemSelectedHasChanged:
if (value.toBool()) { // selected
setTextInteractionFlags(Qt::TextEditorInteraction) ;
} else { // deselected
setTextInteractionFlags(Qt::NoTextInteraction);
}
break;
default:
break;
}

return QGraphicsTextItem::itemChange(change, value);
}

lni
13th February 2010, 16:35
Thanks!

However, the character I enter is taken twice, for instance, I enter "t", it shows up as "tt", I can't seem to find the reason. Here is the code:




class MyScene : public QGraphicsScene
{

void mousePressEvent( QGraphicsSceneMouseEvent *event ) {

currentTextItem = addText ( "" );
currentTextItem->setPos( event->scenePos() );
currentTextItem->setTextInteractionFlags( Qt::TextEditorInteraction );
cursor = currentTextItem->textCursor();

}

void keyPressEvent ( QKeyEvent * event ) {
if ( currentTextItem ) {
cursor.clearSelection();
cursor.movePosition( QTextCursor::NextWord, QTextCursor::KeepAnchor );
cursor.insertText( event->text() );
}

}

private:

QGraphicsTextItem* currentTextItem;
QTextCursor cursor;

};

psih128
13th February 2010, 16:51
You dont need to handle keypress events. The QGraphicsTextItem class actually embeds QTextEdit into a QGraphicsItem and preserves all its functionality. The only thing you need to do is to change that Qt::TextEditorInteraction flag to make it editable.

lni
13th February 2010, 17:04
You dont need to handle keypress events. The QGraphicsTextItem class actually embeds QTextEdit into a QGraphicsItem and preserves all its functionality. The only thing you need to do is to change that Qt::TextEditorInteraction flag to make it editable.

Wow! Thanks!

I spent the entire night digging into the problem, and read QGraphicsTextItem document several times. Not a good documentation in this class....