Search code examples
c++qtqpainterqimage

Drawing line to QImage


I am trying to draw line to QImage and show it in Qlabel. However I have some issues that I cannot solve.

    QPixmap px;
    px.fromImage (imgRaw);  // define in header file QImage imgRaw; 

    QPainter p (&px);
    p.setPen (Qt::red);

    p.drawLine (mouseStart_X, mouseStart_Y, mouseReleased_X, mouseReleased_Y);
    p.end ();

    ui->lblRightImg->setPixmap (px);
    ui->lblRightImg->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    ui->lblRightImg->setScaledContents(true);

When I used this code above it gives such error :

    QPainter::begin: Paint device returned engine == 0, type: 2
    QPainter::setPen: Painter not active
    QPainter::end: Painter not active, aborted

Then I change my code because it tries to draw in null pixmap so after changing code like this:

    QPixmap px(100, 100);
    px.fromImage (imgRaw);  // define in header file QImage imgRaw;

Then it gives noisy image(black and gray broken image)

Could you please help me to solve this issue ?

EDIT :

Also tried:

QPixmap px = QPixmap::fromImage (imgRaw);

Then it gives same image without any drawing..


Solution

  • fromImage is a static function of QPixmap and does not affect your 'object', it returns the pixmap you want. Try using following code to initialize your pixmap:

    QPixmap px = QPixmap::fromImage(imgRaw);