I have a little question about how to implement some sort of graphics editor.
For drawing I use this method:
first I check if left mouse button is clicked, then I draw one pixel at event->pos() on my QPixmap, and after that I call update(); to redraw it. I also paint lines on QPixmap between two dots if the mouse is moved with pressed button(because without it it will just some dots). It works pretty well, but I want to know if there’s more optimized method to do this. Here’s some code(I’ve skipped parts with zooming, joining missing pixels between to pixels etc.)
void Editor::paintEvent(QPaintEvent *event)
{
painter.drawPixmap(QRect(0, 0, image.width() * zoom , image.height() * zoom),
image);
}
void Editor::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
setImagePixel(event->pos());
}
}
void Editor::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons() & Qt::LeftButton)
{
setImagePixel(event->pos(), true);
}
}
void Editor::setImagePixel(const QPoint &pos)
{
QPainter painter(&image);
if(image.rect().contains(i, j))
{
painter.begin(&image);
painter.setPen(primaryColor);
painter.drawPoint(i, j);
painter.end();
}
}
Yes, I would use QPainterPath and its API to draw hand-made shapes. Look at its methods :
moveTo()andlineTo(), which will let you get rid of the drawing logic (missing pixels, etc). It is also very easy to combine with mouse events.Hope this helps.