Show grey level value of pixel in Qt when the mouse is over it

  • Currently I am working on the display of gray level image with zoom feature. I am able to get the position of the pixel and the zoom feature is working well. However I encountered two problems:

    1.) How can I get the grey level value of the pixel that is pointed by the mouse? I only managed to obtain the rgb value through “QRgb rgbValue = pix.toImage().pixel(x,y)”. How can I convert it into grey level value? Or is there any direct way to get the grey level value of the pixel.

    2.) I have implemented “mouseMoveEvent(QMouseEvent *event)” and “setMouseTracking(true)”. However the function of “mouseMoveEvent(QMouseEvent *event)” is not functioning when I move the mouse. What is wrong with my code?

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H

    #include <QMainWindow>
    #include <QGraphicsScene>
    #include <QGraphicsItem>

    namespace Ui {
    class MainWindow;

    class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

    private slots:
    void on_pushButton_clicked();

    void mouseMoveEvent(QMouseEvent * event);

    Ui::MainWindow ui;
    QGraphicsItem* item;
    QPixmap pix;

    #endif // MAINWINDOW_H@


    @#include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)
    //QImage image("E:/ori.jpg");
    QImage image("E:/image_00002.bmp");
    pix = QPixmap::fromImage(image);
    scene = new QGraphicsScene(this);


    delete ui;

    void MainWindow::on_pushButton_clicked()

    void MainWindow::mouseMoveEvent(QMouseEvent *event)
    QPoint local_pt = ui->graphicsView->mapFromGlobal(event->globalPos());
    QPointF img_coord_pt = ui->graphicsView->mapToScene(local_pt);

    double x = img_coord_pt.x();
    double y = img_coord_pt.y();
    /* How can I get a gray level image here */
    QRgb rgbValue = pix.toImage().pixel(x,y);


  • is the image grayscale?

    an 8bit grayscale image represented as a 24bit RGB is simply going to have identical values for each of the R,G,B channels.

    ie. a pixel with grayscale value = 141 (as an arbitrary example) is going to be RGB[141,141,141] so to get the grayscale value, just grab any of the 3 channels.

  • edit: I noticed you asked this same question on qtcenter forums and were told to use:
    Returns a gray value (0 to 255) from the (r, g, b) triplet.
    The gray value is calculated using the formula (r * 11 + g * 16 + b * 5)/32.
    You'll find though, that if your image is grayscale (as you stated) then you do not need to perform this math and my comment above will apply.

    The "math" version is only if you want to convert color to grayscale.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.