Qt World Summit: Submit your Presentation

Aligning QLabel center in QScrollArea causes wrong coordinate reading

  • I have a QLabel for holding picture and the QLabel was placed in a QScrollArea. And I have a eyedropper function that returns color feedback when I mouse over the image. This works when the QLabel was set to align to top and left of the scrollarea, but when I set alignment to AlignCenter, when I mouse over the image, even though the image was displaying in the center, it was actually reading the image as if was still aligning to top and left position.

    For example, I had a white QLabel in a black QScrollArea, the QLabel was100 x 100 and the scrollarea was1000 x 1000. When I aligned center, the label was displayed at between 500 x 500. But when I mouse over it, my eyedropper was reading black. I have to move my mouse to within 100 x 100 from the top left corner in order to pick up the white color again.

  • Lifetime Qt Champion

    You most likely forget some coordinate transformation. Please show us some code.

  • @Christian-Ehrlicher

    void MyScrollArea::sampleColor(const QPoint & mousePos)
        QPoint pos = imageLabel->mapFromGlobal(mousePos);
        QPixmap imagePixmap = imageLabel->pixmap(Qt::ReturnByValue);
        int pixmapWidth = imagePixmap.width();
        int pixmapHeight = imagePixmap.height();
        float normX = (float)pos.x() / (float)pixmapWidth;
        float normY = (float)pos.y() / (float)pixmapHeight;
        emit signalEyeDropped(normX, normY);

    This only works when the label was aligned to top and left.

  • Lifetime Qt Champion

    Where does your mousePos comes from? Are you sure that these are global coordinates?

  • @Christian-Ehrlicher

    I use qDebug() to print out mousePos.x() and mousePos.y() and it's showing my desktop coordinate when I move my mouse around the scrollarea.

  • My sampleColor function was called from the QScrollArea::mouseMoveEvent and the QPoint mousePos was pass in from the mouseEvent there.

    What I'm suspecting is that when the image was loaded, the default alignment AlignTop & AlignLeft kicked in, then the mouseMoveEvent followed and the sampleColor function somehow took a snapshot of the imageLabel, before the AlignCenter setting in the constructor. That's why my mouse was still seeing the image at the pre-aligncenter position in the snapshot.