View Full Version : QGraphicsTextItem - is it a bug there?

17th October 2006, 08:06
Hi, people!

I just wanted to make my text item clear the selection when I take out the focus, but it doesn't work.

// main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QTextCursor>

class MyTextItem : public QGraphicsTextItem
MyTextItem(const QString& name, QGraphicsItem *parent, QGraphicsScene *scene)
:QGraphicsTextItem(name, parent, scene)
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e){
setTextInteractionFlags(Qt::TextEditorInteraction) ;
void focusOutEvent(QFocusEvent *e)
QTextCursor t = textCursor();
t.clearSelection(); // why this doesn't work?
// t.removeSelectedText(); // but this works !!!
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);

int main(int argc, char** argv)
QApplication app(argc, argv);
QGraphicsScene scene;
QGraphicsTextItem *text = new MyTextItem("Hello", 0, &scene);

QGraphicsView view(&scene);
return app.exec();

Have you ever met a problem like this?

17th October 2006, 09:01
QTextCursor t = textCursor();
t.clearSelection(); // why this doesn't work?
setTextCursor(t); // does it work if you add this?

17th October 2006, 09:24
Thanks in advance!

It works. Another problem - I can't find the explanation for this in QAssistant. Is this problem documented somewhere? I'm just curious...

17th October 2006, 12:09
It doesn't need to be documented.
From the docs:

QTextCursor textCursor () const

And your code:

QTextCursor t = textCursor()
You make a copy of the cursor here (note both the const keyword and a lack of a reference in the return value), thus after changing the copy, you have to set it back as the cursor to be used. Reading C++ statements doesn't need to be explained in Qt reference documentation, does it?

18th October 2006, 05:05
Thanks Wysota!
May be you are right, but not absolutely.... because making a copy does not always mean making a deep copy (and actually C++ is not a problem for me).
Indeed, my doubts are produced by the fact that t.removeSelectedText() works but t.clearSelection() doesn't (see the code)! Why there is such a difference between clearing a selection and modifying the text? Why should I expect different behavior for the two IMHO similar methods of a class? I think that it is contrary to OOP concepts...
The only thing I'm searching for is a mention about what methods need a call to setCursor() and which need not... just for the sake of clarity.

18th October 2006, 09:48
In Qt4 all copies are "deep" when you modify an object (copy on write for all shared classes).