PDA

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



Tair
17th October 2006, 07: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
{
public:
MyTextItem(const QString& name, QGraphicsItem *parent, QGraphicsScene *scene)
:QGraphicsTextItem(name, parent, scene)
{
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
}
protected:
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e){
setTextInteractionFlags(Qt::TextEditorInteraction) ;
setFocus();
QGraphicsTextItem::mouseDoubleClickEvent(e);
}
void focusOutEvent(QFocusEvent *e)
{
QTextCursor t = textCursor();
t.clearSelection(); // why this doesn't work?
// t.removeSelectedText(); // but this works !!!
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
QGraphicsTextItem::focusOutEvent(e);
}
};

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

QGraphicsView view(&scene);
view.setDragMode(QGraphicsView::RubberBandDrag);
view.show();
return app.exec();
}


Have you ever met a problem like this?

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

Tair
17th October 2006, 08: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...

wysota
17th October 2006, 11: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?

Tair
18th October 2006, 04: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.

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