QPainter. Draw line
Asked Answered
R

3

12

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?

Radioactive answered 10/7, 2014 at 8:48 Comment(0)
U
17

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();
    [..]
Uneven answered 10/7, 2014 at 9:1 Comment(0)
B
16

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();
}
Barnes answered 15/7, 2014 at 21:28 Comment(0)
T
1

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.

Tweeddale answered 10/7, 2014 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.