QPainter. Draw line

39,642

Solution 1

You can not paint outside of the paintEvent() function, at least on Windows and Mac OS. However you can override your MainWindow class' paintEvent() function to draw the line there. For example:

class Widget : public QWidget
{
protected:
    void paintEvent(QPaintEvent *event)
    {
        QPainter painter(this);
        painter.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
        painter.drawLine(0, 0, 200, 200);
    }
};

And the usage:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Widget w;
    w.show();
    [..]

Solution 2

You can't paint on a widget outside of a paint event. But you can paint at any time on a non-widget, such as on a QImage, QPixmap or a QPicture:

screenshot

#include <QtWidgets>

int main(int argc, char *argv[])
{
   QApplication a(argc, argv);

   QPicture pi;
   QPainter p(&pi);   
   p.setRenderHint(QPainter::Antialiasing);
   p.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
   p.drawLine(0, 0, 200, 200);
   p.end(); // Don't forget this line!

   QLabel l;
   l.setPicture(pi);
   l.show();
   return a.exec();
}

Solution 3

Widgets can be painted on only in their respective paint event. You can draw on a pixmap in any function, but you need to show the result in the widget paint event.

From the doc:

Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent(); that is unless the Qt::WA_PaintOutsidePaintEvent widget attribute is set.

Share:
39,642
Ufx
Author by

Ufx

Updated on July 27, 2022

Comments

  • Ufx
    Ufx almost 2 years

    I am trying to draw line.

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        QPainter painter(&w);
        painter.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
        painter.drawLine(0, 0, 200, 200);
    
        return a.exec();
    }
    

    But there is nothing painting on the window. What is wrong?