This question may or may not relate to QGraphicsItemGroup
- I have never seen this behavior before though....
Briefly: I am deselecting an item, yet the action doesn't take place unless I call the read-only scene().selectedItems()
- even if I don't use it.
Details:
I have a custom QGraphicsScene
class, that has to perform a lot of operations on the selectedItems()
.
If items are in a group, they should not be used in any operations - only the group should be used.
So I create my addToGroup()
method to perform what I need:
void addToGroup(QList<QGraphicsItem *> children) {
foreach(QGraphicsItem* child, children)
{
child->setSelected(false);
QGraphicsItemGroup::addToGroup(child);
}
}
Unfortunately, the items refuse to get deselected !
And then, I added debug messages after each line - and found that adding debug messages changes the outcome !
void addToGroup(QList<QGraphicsItem *> children) {
foreach(QGraphicsItem* child, children)
{
child->setSelected(false);
scene()->selectedItems(); // this makes it work !
QGraphicsItemGroup::addToGroup(child);
}
}
Calling scene()->selectedItems();
- which should be read--only - makes the items actually get deselected !
Please allow me to make sense of this !
Full sample code:
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsRectItem>
#include <QDebug>
class Item {
public:
Item(int id) {
m_id = id;
}
private:
int m_id;
};
class RectItem: public QGraphicsRectItem, public Item
{
public:
RectItem(int id) : Item(id) {
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
setRect(QRectF(0,0,100,100));
setPos(QPointF(10+110*id,10));
setSelected(true);
}
};
class GroupItem: public QGraphicsItemGroup, public Item
{
public:
GroupItem(int id) : Item(id) {
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable);
}
void addToGroup(QList<QGraphicsItem *> children) {
foreach(QGraphicsItem* child, children)
{
child->setSelected(false);
//scene()->selectedItems().size();
QGraphicsItemGroup::addToGroup(child);
}
}
};
class MyScene: public QGraphicsScene
{
public:
MyScene() {}
void group() {
GroupItem* g = new GroupItem(items().size());
addItem(g);
g->addToGroup(selectedItems());
g->setSelected(true);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyScene s;
QGraphicsView view(&s);
s.setSceneRect(0, 0, 230, 120);
view.show();
RectItem* r0 = new RectItem(0);
s.addItem(r0);
RectItem* r1 = new RectItem(1);
s.addItem(r1);
s.group();
qDebug() << "Should only have 1 (group) selected out of 3\nTotal items:" << s.items().size() << "; Selected items:" << s.selectedItems().size();
return app.exec();
}