Search code examples
c++qtqwidgetqimage

Get QImage pixel coordinates


I currently draw a QImage to a QWidget with the following code:

QPainter c(this);
const QRect& cw = c.window();

c.setRenderHint(QPainter::SmoothPixmapTransform, cw.width() < scale);
c.drawImage(cw, image);

The issue is now that the image has been properly scaled to fit in the QWidget, I would like to get the pixel coordinates on the QImage based on the QWidget coordinates. Without scaling this would be fairly trivial, as widget pixels correspond directly to QImage coordinates. Ultimately, a way to translate which pixel on the QWidget corresponds to the pixel in the QImage when scaled is ideal. Any advice is much appreciated!


Solution

  • What you have implemented is an escalation, to recover a coordinate we can use QTransform as I show below:

    QTransform tr;
    tr.scale(image.width()*1.0/cw.width(), image.height()*1.0/cw.height());
    QPoint imagePoint = tr.map(widgetPoint);