Search code examples
qtqgraphicsitemqpixmap

QGraphicsPixmapItem is one pixel too large if I set the item selectable


My QGraphicsPixmapItem has to report a correct size - its initial size should match the original image size.

I notice something odd if I make the item selectable: the size reported is one pixel too large.

Is this to be expected ?
Will this behavior be consistent for all QGraphicsPixmapItems that are set selectable ?
(And can I therefore override the boundingRect() to subtract 1 from the size reported by the QGraphicsPixmapItem::boundingRect() each time ?)

Simple check, with any image:

QGraphicsPixmapItem p;
p.setFlags(QGraphicsItem::ItemIsSelectable);
QString fileName = QFileDialog::getOpenFileName(0, QObject::tr("Open Image File"),
                 QString(), QObject::tr(
                 "Png files (*.png);;Jpeg files (*.jpg *.jpeg);;Bitmap files (*.bmp)"));
QPixmap pixmap(fileName);
qDebug("%d %d", pixmap.size().width(), pixmap.size().height());
p.setPixmap(pixmap);
qDebug("%f %f", p.boundingRect().width(), p.boundingRect().height());

Solution

  • This is expected behavior. If you look at the source code, you will see that it adds half a pixel to each direction when the ItemIsSelectable flag has been set:

    if (d->flags & ItemIsSelectable) {
        qreal pw = 1.0;
        return QRectF(d->offset, d->pixmap.size()).adjusted(-pw/2, -pw/2, pw/2, pw/2);
    }