Reputation: 161
I try to accomplish a simple erase functionality when drawing lines in Qt (not bitmaps but true lines).
I'm e.g. drawing a black line in one "layer" and a read line in another "layer". Then I want to erase some of the red line, so I paint a white line. However I want to be able to see some of the black line where the intersect.
This is my situation:
I want to accomplish something like this:
I've been playing around with creating a customline class that inherits from a QGraphicsLine and implements the paint event to be able to control the composition modes - but I haven't yet found the right solution.
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
_scene = new QGraphicsScene(this);
ui->graphicsView->setScene(_scene);
_blackPen = QPen(Qt::black);
_blackPen.setWidth(40);
_redPen = QPen(Qt::red);;
_redPen.setWidth(40);
_eraserPen = QPen(Qt::white);
_eraserPen.setWidth(10);
_scene->addItem(new CustomLine(0,0,100,100, _blackPen, QPainter::CompositionMode_Source));
_scene->addItem(new CustomLine(0,100,100,100, _redPen, QPainter::CompositionMode_Source));
_scene->addItem(new CustomLine(0,100,100,100, _eraserPen, QPainter::CompositionMode_Source));
}
#include "customline.h"
#include <QPainter>
CustomLine::CustomLine(qreal x, qreal y, qreal x2, qreal y2, QPen &pen, QPainter::CompositionMode mode)
{
_x = x;
_y = y;
_x2 = x2;
_y2 = y2;
_pen = pen;
_mode = mode;
}
void CustomLine::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->setPen(_pen);
painter->setCompositionMode(_mode);
painter->drawLine(_x,_y, _x2, _y2);
}
Any suggestions?
Upvotes: 0
Views: 828
Reputation: 2444
There may be a way to do it with compositing, but you might also try using an outline of the red line, and to get that, use QPainterPathStroker. Create a path containing the line, and then use the stroker to create an outline around that. The code will be something like:
QPainterPath path;
path.lineTo (...);
QPainterPathStroker stroker;
QPainterPath outline = stroker.createStroke (path).simplified ());
painter.drawPath (outline);
You'll probably need to play with this to get what you want. When I first started using QPainterPathStroker, I didn't find it to be terribly intuitive.
Upvotes: 1