Important: Please read the Qt Code of Conduct -

Getting QPainter surface color at a specific point

  • I want to dynamically color text on a custom drawn widget. The widget displays a grid of shapes of a potentially large number of colors along with data associated with the location of the shape and I want to test the color of an area (which can currently be determined by a single pixel) to decide whether to make the text white or black (based on average of the r, g, and b values).

    The problem is that QPainter doesn't seem to have a way to do this and since changes to the appearance of the widget can be animated to some degree (when scrolling or when zoom changes), I am worried that drawing to an image and copying the image will take too much processing time.

    Is there a way to directly get the color of a specific point on the QPainter surface? Or will I need to translate the point to screen coordinates and get the color using the OS API?

  • Lifetime Qt Champion

    What about just grabbing the area to a QImage and use
    the pixel functions from QImage?
    I assume you dont have to resample over and over?

  • It's not a single text location. This is a repeating pattern, writing a data overlay (such as coordinates or some other value) for each cell (shape) in the picture. That would mean creating (allocating), copying, and destroying an average of 18,000 images every draw. That seems terribly time consuming.

  • Lifetime Qt Champion

    ok, i see. If drawing to QImage is too slow then
    maybe native api is fastest option.

    Im not aware of anything like
    HDC dc = GetWindowDC(NULL);
    COLORREF color = GetPixel(dc, _x _y );
    from Windows API, in Qt.

Log in to reply