Kanghu
Kanghu

Reputation: 591

Qt drawPixmap isn't drawing what I expect

I'm trying to make a Paint application in C++ with Qt. Everytime I click or click & drag the mouse, the program will draw something on a pixmap. After that, it updates the window calling paintEvent(), which will draw the pixmap onto the window.

void QPaintArea::mousePressEvent(QMouseEvent *event){
    startpoint = event->pos();
    drawPoint(startpoint);
    is_pressed = true;
}

void QPaintArea::mouseReleaseEvent(QMouseEvent *event){
    is_pressed = false;
}

void QPaintArea::mouseMoveEvent(QMouseEvent *event){
    if(is_pressed == true){
        endpoint = event->pos();
        drawLine(startpoint, endpoint);
        startpoint = endpoint;
    }
    else{
        return;
    }
}

void QPaintArea::paintEvent(QPaintEvent *event){
    QDesktopWidget *desktop = QApplication::desktop();
    int x = (desktop->width() - 800) / 2;
    int y = (desktop->height() - 600) / 2;
    QPainter painter(this);
    QRect target(QPoint(x, y - 35), QSize(800, 600));
    QRect dirtyrect(QPoint(0,0), QSize(800, 600));
    painter.drawPixmap(target, *pixmap, dirtyrect);
}

The problem is that, the program is not printing the pixmap onto the window as expected. For example, I press the mouse at x: 17, y: 82 trying to draw something. The program will print what I drew but at an offset location, like x + 20, y.

Maybe I don't fully understand how QRect or drawPixmap works, but the pixmap is 800x600. "dirtyrect" is supposed to save the entire pixmap (starting a x: 0, y: 0, and the size 800x600).

Upvotes: 2

Views: 6188

Answers (1)

Kamil Klimek
Kamil Klimek

Reputation: 13130

drawPixmap(target, pixmap, source) paints on target rect of painter area (QPaintArea in this case) source part of pixmap. So you paint whole pixmap (0,0,800,600) at some (x,y-35,800,600) rect of QPaintArea. If you want to paint whole pixmap on whole QPaintArea just use drawPixmap(QPoint(0,0), *pixmap).

// EDIT

But if you expected, that pixmap will be painted with some offset from QPaintArea top left corner, then your calculations are wrong, and if you wont explain what did you want to achieve we won't be able to help you. Explain us your calculations of x,y (and magic -35 for y), and maybe we will be able to figure something out

// EDIT You don't have to use window offsets like -35 if you're painting on widget. 0,0 of the widget is not top left corner of window frame, but of widget contents. How do you expect it to behave on other platforms?

If you want to paint it in the middle of your window simply use:

void QPaintArea::paintEvent(QPaintEvent *event){
    QPoint middle = geometry.center();
    int x = middle.x() - 800/2; // probably best would be pixmap->width()/2
    int y = middle.y() - 600/2; // probably best would be pixmap->height()/2
    QPainter painter(this);
    painter.drawPixmap(QPoint(x,y), *pixmap);
}

Upvotes: 3

Related Questions