Mitch
Mitch

Reputation: 24406

QGraphicsScene::items returns no items for a given rect

I'd like to select all items within a certain area and change their opacity. I'm using QGraphicsScene::items() to do this, but I can't seem to get it to return any items. An example:

#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QDebug>
#include <QKeyEvent>
#include <QGraphicsPixmapItem>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
  , scene(new QGraphicsScene())
{
    ui->setupUi(this);

    ui->graphicsView->setScene(scene);
    ui->graphicsView->installEventFilter(this);
    ui->graphicsView->show();

    for (int y = 0; y < 20; ++y) {
        for (int x = 0; x < 20; ++x) {
            QPixmap pixmap("desert.png");
            QGraphicsPixmapItem* newItem(scene->addPixmap(pixmap));
            newItem->setPos(x * 25, y * 25);
            newItem->setOpacity(0.0);
            qDebug() << newItem;
        }
    }
}

MainWindow::~MainWindow()
{
    delete ui;
    delete scene;
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    if(event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Space) {
            QRectF rect(0, 0, 25 * 3, 25 * 3);
            QList<QGraphicsItem*> items(scene->items(rect, Qt::ContainsItemBoundingRect, Qt::AscendingOrder));
            qDebug() << items;
            foreach (QGraphicsItem *item, items) {
                item->setOpacity(1.0);
            }
        }
        return true;
    }
    return QObject::eventFilter(obj, event);
}

I'm pretty sure that I don't need to supply the deviceTransform argument, and I know that the rect I'm passing in should cover 9 tiles. What am I doing wrong?

Upvotes: 2

Views: 1575

Answers (1)

Andreas Fester
Andreas Fester

Reputation: 36630

When creating the items, you already set their opacity to 0 so that they are not visible - items() returns visible items only, see http://qt-project.org/doc/qt-4.8/qgraphicsscene.html#items-10:

Returns all visible items ...

Set the opacity to a value > 0 in your constructor, e.g.

newItem->setOpacity(0.001);

When now pressing the space bar, the four items in the given rectangle will appear.

Upvotes: 2

Related Questions