PDA

View Full Version : [Solved] Selecting text with mouse in a QGraphicsTextItem



pherthyl
11th August 2007, 18:50
I'm having problems getting text selectable with the mouse in a QGraphicsTextItem if I put it in a scene visualized by a view that has rubber band selection enabled.

Here's a minimal example:



#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QGraphicsRectItem>

class TestView : public QGraphicsView {
public:
TestView(QWidget* parent) : QGraphicsView(parent) {
setScene(new QGraphicsScene(this));
QGraphicsTextItem* ti = new QGraphicsTextItem("test");
ti->setTextInteractionFlags(Qt::TextEditorInteraction) ;
scene()->addItem(ti);
setDragMode(QGraphicsView::RubberBandDrag);
QGraphicsRectItem* ri = new QGraphicsRectItem(QRectF(20,20,30,30));
ri->setFlags(QGraphicsItem::ItemIsMovable);
ri->setBrush(Qt::red);
scene()->addItem(ri);
}
};


Running that example, you can focus the text box, and edit with the keyboard, but you can't select text with the mouse. If you try, a rubber band will be drawn in the background.
If you disable the rubber band selection, everything works fine.

The second QGraphicsItem in that code is just to illustrate why I don't understand this behaviour. In that case, the item is movable, so it handles the mouse drag events itself. When you move the rectangle around, there is no rubber band drawn, because the event is handled by the rectangle to move. So I find it very illogical that the text item behaves differently. It also should handle mouse drags, and yet passes them on to the view instead.

But inconsistent behaviour or not, is there any way I can fix this? How do I get an editable text item, and yet still allow rubber band selection in the graphics view?

marcel
11th August 2007, 19:31
QGraphicsTextItem* ti = new QGraphicsTextItem("test");
ti->setTextInteractionFlags(Qt::TextEditorInteraction) ;
ti->setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | ti->flags());

This works for me.
ItemIsSelectable does the trick.
ItemIsFocusable lets you input text with the keyboard.

Regards

pherthyl
11th August 2007, 20:10
Brilliant! Thanks so much. Works like a charm.