QGraphicsLineItem :: paint () artifacts
I have my own class that inherits from QGraphicsLineItem
and overrides the method paint()
for drawing a thick line with an arrow:
void MyGraphicsItem::paint( QPainter* aPainter,
const QStyleOptionGraphicsItem* aOption,
QWidget* aWidget /*= nullptr*/ )
{
Q_UNUSED( aOption );
Q_UNUSED( aWidget );
QLineF cLine = line();
aPainter->setPen( QPen( Qt::black, 6, Qt::SolidLine ) );
aPainter->drawLine( cLine );
qreal lineAngle = cLine.angle();
const qreal radius = 2.0;
QLineF head1 = cLine;
head1.setAngle(lineAngle+32);
head1.setLength( 12 );
QLineF head2 = cLine;
head2.setAngle(lineAngle-32);
head2.setLength( 12 );
aPainter->drawLine( head1 );
aPainter->drawLine( head2 );
aPainter->setPen( QPen( Qt::yellow, 2, Qt::SolidLine ) );
aPainter->drawLine( cLine );
aPainter->drawLine( head1 );
aPainter->drawLine( head2 );
}
This seems to be causing the artifacts to render when I draw an element around the scene. From what I can tell, because I set the thickness to QPen
, what leads me to believe that I should somehow draw outside of the elements rectangle?
What is causing my rendering problem and how can I solve it?

Note that the background is not redrawn on the image - this happens with any other objects in the scene that are also dragged by the arrow.
Edit: I think this is actually my problem:
Subclassing QGraphicsView and setting drawBackground
Edit again: The issue seems to be background related, but using full blown updates port updates kill performance, so I came up with this, which seems to increase CPU usage by 3% rather than binding one core to 100% use.
// This code lives in the QGraphicsScene constructor, doesn't have to be there though since QGraphicsScene::setBackgroundBrush is public.
int gridSizeX = 25;
int gridSizeY = 20;
QImage singleGrid( gridSizeX, gridSizeY, QImage::Format_RGB32 );
singleGrid.fill( Qt::white );
{
QPainter painter( &singleGrid );
// Lighter background
painter.setPen( QPen( QColor( 240, 240, 240 ) ));
qreal midx = gridSizeX / 2;
qreal midy = gridSizeY / 2;
painter.drawLine( 0, midy, gridSizeX, midy );
painter.drawLine( midx, 0, midx, gridSizeY );
// Darker foregound
painter.setPen( QPen( QColor( 180, 180, 180 ) ));
painter.drawRect( 0, 0, gridSizeX, gridSizeY );
painter.end();
}
QBrush brushBackground( singleGrid );
setBackgroundBrush( brushBackground );
The scene then repeats that brush throughout, resulting in the same mesh background effect that even works when scaling / scaling.:.)
a source to share
When overriding the paint () function, you also need to override QGraphicsItem :: boundingRect () in your class to define the outer bounds of your custom graphic item. If you go outside, you will get rendering artifacts. Right now, you are dependent on the QGraphicsLineItem implementation of the boundingRect () function, which of course is unaware of your paint () implementation. See http://doc.qt.digia.com/main-snapshot/qgraphicsitem.html#boundingRect for details .
a source to share