关于C#:QGraphicsLineItem :: paint()工件

QGraphicsLineItem::paint() artifacts

我有自己的类,该类继承自QGraphicsLineItem,并覆盖了paint()方法以绘制带有箭头的粗线:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 );
}

当我在场景中绘制项目时,这似乎会导致渲染失真。据我所知,因为我已经在QPen上设置了厚度,这使我相信必须以某种方式在矩形的外部进行绘制?

是什么导致我的渲染问题,我该如何解决?

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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 );

然后,场景在所有位置重复此笔刷,从而产生相同的网格背景效果,甚至在缩放/缩放时也可以按预期工作。 :)。


当重写paint()函数时,还需要重写类中的QGraphicsItem :: boundingRect()来定义自定义图形项的外部边界。如果在边界之外绘制,则最终会出现渲染瑕疵。现在,您依赖QGraphicsLineItem的boundingRect()的实现,它当然不知道您对paint()函数的实现。有关详细信息,请参见http://doc.qt.digia.com/main-snapshot/qgraphicsitem.html#boundingRect。