QPainter. Draw line
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.
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();
[..]
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
:
#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();
}