QPainter Draw Line

Before to draw line on a qwidget,

override the paintEventFunction:

virtual void paintEvent(QPaintEvent* p) override;

implement the function:

void DrawApplication::paintEvent(QPaintEvent* p)
{
   QPainter painter(this); //class must be implemented from QWidget
   painter.drawLine(30, 40, 80, 90);
   painter.drawLine(QPoint(80, 100), QPoint(200, 300));
}

Result:

For a styled line:

void DrawApplication::paintEvent(QPaintEvent* p)
{
      QPainter painter(this);

      QPen pen;
      pen.setColor(QColor("#355698"));
      pen.setWidth(3);

      painter.setPen(pen);

      painter.drawLine(30, 40, 80, 90);

      pen.setWidth(13);
      pen.setColor(Qt::red);
      painter.setPen(pen);

      painter.drawLine(QPoint(80, 100), QPoint(200, 300));
}

Result:

Leave a Reply

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