我想选择某个区域内的所有项目并更改它们的不透明度。我曾经QGraphicsScene::items()
这样做过,但我似乎无法让它返回任何物品。一个例子:
#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);
}
我很确定我不需要提供deviceTransform
参数,而且我知道我传入的矩形应该覆盖 9 个图块。我究竟做错了什么?