Drawing a point over an image on QLabel.



  • I displayed a picture on QLabel and wanted to take coordinates and paint a point on image on mouse click event. I am able to get coordinates but painter is painting point below my image on label, i want it above my image.

    My code is :

    imageviewer.h

    @#include <QPushButton>

    class imageviewer : public QLabel
    {
    Q_OBJECT

    public:
    explicit imageviewer(QWidget *parent = 0);

    private slots:

    void mousePressEvent(QMouseEvent * e);
    void paintEvent(QPaintEvent * e);
    

    private:

    QLabel *label1 ;
    int mFirstX;
    int mFirstY;
    bool mFirstClick;
    bool mpaintflag;
    

    };

    #endif
    @

    imageviewer.cpp
    @

    #include <QtGui>
    #include <QHBoxLayout>
    #include <QVBoxLayout>
    #include "imageviewer.h"
    #include <QDebug>

    imageviewer::imageviewer(QWidget *parent)
    : QLabel(parent)
    {

    label1 = new QLabel;
    label1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    QPixmap pm1("/home/nishu/Pictures/img_0002.jpg");
    label1->setPixmap(pm1);
    label1->adjustSize();
    label1->setScaledContents(true);
    
    QHBoxLayout *hlayout1 = new QHBoxLayout;
    hlayout1->addWidget(label1);
    
    setLayout(hlayout1);
    

    }

    void imageviewer :: mousePressEvent(QMouseEvent *e)
    {
    mFirstX=0;
    mFirstY=0;
    mFirstClick=true;
    mpaintflag=false;

    if(e->button() == Qt::LeftButton)
            {
                //store 1st point
                if(mFirstClick)
                {
                    mFirstX = e->x();
                    mFirstY = e->y();
                    mFirstClick = false;
                    mpaintflag = true;
                    qDebug() << "First image's coordinates" << mFirstX << "," << mFirstY ;
                    update();
    
                }
               
            }
    

    }

    void imageviewer :: paintEvent(QPaintEvent * e)
    {

    QLabel::paintEvent(e);
    
    if(mpaintflag)
    {
               QPainter painter(this);
               QPen paintpen(Qt::red);
               paintpen.setWidth(10);
               QPoint p1;
               p1.setX(mFirstX);
               p1.setY(mFirstY);
               painter.setPen(paintpen);
               painter.drawPoint(p1);
            }
    

    }
    @
    main.cpp

    @
    #include "imageviewer.h"
    #include <QApplication>

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    imageviewer w;
    w.showMaximized();

    return a.exec&#40;&#41;;
    

    }
    @


Log in to reply
 

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