[SOLVED] How to add outline to QGraphicsLineItem?

Table of Contents

Issue

I want to have a QGraphicsLineItem where it is outlined by a certain color.

I have tried using

QGraphicsLineItem::setColor(QColor(...))

However this only paints the inside.

What function must I call to create an outline?

Being more specific, let’s say this is a normal QGraphicsLineItem

--------------------------------------
    10px
    green QGraphicsLineItem
--------------------------------------

What I want is a completely different (solid) color outside of the boundaries, like so,

--------------------------------------
2px blue 
--------------------------------------
10px
green
--------------------------------------
2px blue
--------------------------------------

So a drop shadow effect won’t work, hopefully this is clear.

Solution

Solution 2

Another way to add an outline is to use QPainter::strokePath. For that you have to subclass QGraphicsLineItem and reimplement the paint method.

Note: This approach is more complex, as it requires subclassing, but it allows more freedom, including setting the ticknes and the color of the outline.

Here is an example of how to do that:

void OutLineItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QPainterPath outline;

    outline.moveTo(line().p1());
    outline.lineTo(line().p2());

    painter->save();
    painter->setRenderHint(QPainter::Antialiasing);
    painter->strokePath(outline, QPen(m_outlineColor, 2*m_outlineWidth + pen().width()));
    painter->setPen(pen());
    painter->drawLine(line());
    painter->restore();
}

The full code of the example I have prepared for you is available on GitHub.

This example produces the following result:

Window with a thick green line with a solid blue outline

Answered By – scopchanov

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *