PDA

View Full Version : QPainter doesn't paint



Blitzor DDD
15th July 2016, 13:54
Hello!

I am trying to paint a simple plot (sin) on a screen.
Maybe my method is a bit wierd I don't know, this is my first paint-expirience.
Hower, I encountered a problem.

Here is my code:

.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLabel>
#include <QPainter>



class Widget : public QWidget
{
Q_OBJECT
const double pi = 3.14159;
public:
Widget(QWidget *parent = 0);
~Widget();

private:
QLabel *Hi;
QPainter *paint;
virtual void paintEvent(QPaintEvent * );
};

#endif // WIDGET_H


.cpp

#include "widget.h"
#include <QWidget>
#include <cmath>

Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setGeometry(100,100,800,500);
paint = new QPainter(this);
}

Widget::~Widget()
{

}

void Widget::paintEvent(QPaintEvent * )
{
paint-> setPen(QPen(Qt::red));

for(int i=0;i<1000;i++)
{
qreal x=sin(pi/6+i);
qreal y=sin(pi/6+i);
paint->drawPoint(QPointF(x,y));
}
}


At first, I just tried to paint in .cpp without void Widget::paintEvent(QPaintEvent * ) like this:

#include "widget.h"
#include <QWidget>
#include <cmath>

Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->setGeometry(100,100,800,500);
paint = new QPainter(this);
paint-> setPen(QPen(Qt::red));

for(int i=0;i<1000;i++)
{
qreal x=sin(pi/6+i);
qreal y=sin(pi/6+i);
paint->drawPoint(QPointF(x,y));
}
}

Widget::~Widget()
{

}


It didn't work. Then I looked throught the Internet and found out that one can paint only in void Widget::paintEvent(QPaintEvent * ), and besides this method must be virtual. I have changed this, it didn't help either.

then I found that paint(this) should be changed to this paint.begin(viewport());
done and viewport() "no matching fucntion to call"

What seems to be the problem here? and could someone help me to fix that?
Thank you in advance!

ChrisW67
15th July 2016, 21:56
Typically you allocate a QPainter on the stack inside paintEvent(). As it goes out of scope QPainter::end() will ensure all painting is completed and resources freed.
All 1000 of your x,y coordinates has a value between 0 and 1: they all map to a single pixel.
The paintEvent() function is normally protected.

anda_skoa
16th July 2016, 11:28
Typically you allocate a QPainter on the stack inside paintEvent().

That is actually the only supported option for painting onto a widget, due to how the widget buffering is implemented internally.

This code should even have generated a warning at runtime (creating a QPainter on the widget outside of paintEvent()).

Creating a painter on viewport() is for painting in a QAbstractScrollArea derived class, in normal widgets the paint device is "this".

Cheers,
_