'How to add outline to QGraphicsLineItem?

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 1:[1]

Solution 1

One way to add an outline to QGraphicsLineItem is to use QGraphicsDropShadowEffect with zero offset.

Note: This approach does not require subclassing, but it is not so robust, as it does not allow the tickness to be set precisely and the outline is not solid. However, in some cases this might work just fine.

Here is an example of how to do that:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    auto *view = new QGraphicsView(this);
    auto *item = new QGraphicsLineItem(50, 50, 250, 150);
    auto *effect = new QGraphicsDropShadowEffect(this);

    effect->setColor(Qt::blue);
    effect->setOffset(0);
    effect->setBlurRadius(10);

    item->setPen(QPen(Qt::green, 10));
    item->setGraphicsEffect(effect);

    view->setScene(new QGraphicsScene(this));
    view->scene()->addItem(item);

    setCentralWidget(view);
    resize(300, 200);
}

This example produces the following result:

Window with a thick green line with a glowing blue outline

Solution 2:[2]

You can addpath on QGraphicsscene,Make sure that the coordinates of the point are in the scene coordinate system

void Myclass::DrawOutline()
{
    int cntLeft = ptLeft.count();
    int cntRight = ptRight.count();
    if (cntLeft && cntRight)
    {
        QPainterPath polygonPath;
        QVector <QPoint> points;

        for (int i = 0;i < cntLeft;i++)
        {
            QPoint pos;
            points.push_back(pos);
        }

        for (int i = cntRight-1;i >=0;i--)
        {
            QPoint pos;
            points.push_back(pos);
        }
        polygonPath.addPolygon(QPolygon(points));
        polygonPath.closeSubpath();
        QPen pen;
        pen.setColor(QColor(0,0,0));
        pen.setWidth(1);
        m_scene->addPath(polygonPath, pen);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Edgar999777