[Solved]Problem selecting a QGraphicsItem child.
-
Hi,
To select a QGraphicsItem child I call child->setSelected(true) in itemChange function every time the selected state changes. But when I release the mouse at the same mouse press point/position, the child item is deselected.
The strange thing is that the child item is no deselected if I move the mouse before I release the mouse:
Press the mouse into the parent item.
Move the mouse (pressing).
Release the mouse (diferent from press point/position).
Child is no deselected, it's selected.
Why is this happening?
Here is the code if you want to try it... :)
@
#include <QtGui>
#include <QtCore>class Item : public QGraphicsRectItem
{
public:
Item(const QRectF &rect, QGraphicsItem *parent = 0) :
QGraphicsRectItem(rect, parent) {// Create the item _otherItem = new QGraphicsRectItem(20, 20, 10, 10, this); // Configure the item ~ Is selectable _otherItem->setPen(QPen(Qt::black)); _otherItem->setBrush(QBrush(Qt::green)); _otherItem->setFlag(QGraphicsItem::ItemIsSelectable, true); }
protected:
QVariant itemChange(GraphicsItemChange change, const QVariant &value) {// If the item's selected state changes if (change == QGraphicsItem::ItemSelectedChange) { // If is selected if (value.toBool() == true) { // Show _otherItem and select it _otherItem->setSelected(true); } else { _otherItem->setSelected(false); } } return QGraphicsRectItem::itemChange(change, value); }
private:
QGraphicsRectItem *_otherItem;
};int main(int argc, char *argv[])
{
QApplication app(argc, argv);QGraphicsScene scene; // Create and configure the item ~ Is selectable Item *rect = new Item(QRectF(0, 0, 50, 50)); rect->setPen(QPen(Qt::black)); rect->setBrush(QBrush(Qt::red)); rect->setFlag(QGraphicsItem::ItemIsSelectable, true); scene.addItem(rect); QGraphicsView view(&scene); view.show(); return app.exec();
}
@Thanks.
-
Hi,
The answer is in qgraphicsitem.cpp file at mouseReleaseEvent function, the comment says:
@
if (event->scenePos() == event->buttonDownScenePos(Qt::LeftButton)) {
// The item didn't move
if (multiSelect) {
setSelected(!isSelected());
} else {
...
// Clear everything but this item. Bypass
// QGraphicsScene::clearSelection()'s default behavior by
// temporarily removing this item from the selection list.
...
scene->clearSelection();
...
}
}
@Mario.