3
votes

For some time I'm developing a simple drawing and painting app with Qt/C++.

Currently I'm using QPainter::drawLine() to draw, and it works fine.

What I want to do is drawing with pixmap brushes, which in a way I can do. I can draw with single color filled pixmaps using QPainterPath and QPainter::strokePath(). I stroke the path with a pen using a brush with the pixmap.

In case you're still reading, my problem is, if I use a QPen and QPainter::strokePath() I get a line with tiled brush. But I want the pixmap to be drawn along the line. Like the image based brushes in some image editors. I can do that with drawRect(), but that draws the pixmaps apart.

If you understand my problem from the gibberish I wrote, how can I draw a line with a pixmap brush?

Edit: Here's what I do currently:

void Canvas::mouseMoveEvent(QMouseEvent *event)
{
    polyLine[2] = polyLine[1];
    polyLine[1] = polyLine[0];
    polyLine[0] = event->pos();

    //Some stuff here
    painter.drawLine(polyLine[1], event->pos());
}

This is what I tried:

void Canvas::mouseMoveEvent(QMouseEvent *event)
{
    QPen pen(brush, brushSize, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin);
    //Some stuff here
    path.lineTo(event->pos());
    painter.strokePath(path, pen); 
    //This creates a fine line, but with a tiled brush
}

To draw a pixmap along mouse movement, I tried

void Canvas::mouseMoveEvent(QMouseEvent *event)
{
    //Some stuff
    QBrush brush(QPixmap(":images/fileName.png"));
    painter.setBrush(brush);
    painter.setPen(Qt::NoPen);
    painter.drawRect(QRect(event->pos() - brushSize / 2, event->pos() - brushSize / 2, brushSize, brushSize));
    //This draws the pixmaps with intervals.
}
1
possible duplicate of Line interpolation in Qt?UmNyobe
It's a possible duplicate, because answer applies them both, yes, but the question and the title are a bit different, and I think this would be easier to find on a google search if you're looking for an answer to pixmap brushes. For one thing, during my search for an answer, I couldn't find that other answer. After only I registered with StackOverflow I saw it.user4516901
It is the same issue presented differently. Indeed your question is better worded.UmNyobe

1 Answers

4
votes

Nevermind, I've found the solution here

The accepted answer shows how to draw a pixmap repeatedly along a path. That's great. For reference, I'll copy the code here:

QPointF lastPosition, currentPosition;
qreal spacing;

void draw() {
    QPainterPath path;
    path.moveTo(lastPosition);
    path.lineTo(currentPosition);
    qreal length = path.length();
    qreal pos = 0;

    while (pos < length) {
        qreal percent = path.percentAtLength(pos);
        drawYourPixmapAt(path.pointAtPercent(percent)); // pseudo method, use QPainter and your brush pixmap instead
        pos += spacing;
    }
}