How to draw with QPainter?

I recently started learning Qt.
I did not understand how to draw using the QPainter class. Say I want to just put some dots in a window:

 class PointDrawer: public QWidget { Q_OBJECT private: QPainter p; public: PointDrawer(QWidget* obj=0): QWidget(obj), p(this) {} virtual void paintEvent(QPaintEvent*) { p.setPen(QPen(Qt::black, 3)); int n = 8; while(...) { qreal fAngle = 2 * 3.14 * i / n; qreal x = 50 + cos(fAngle) * 40; qreal y = 50 + sin(fAngle) * 40; p.drawPoint(QPointF(x, y)); i++; } } } int main(int argc, char *argv[]) { QApplication app(argc, argv); PointDrawer drawer; drawer.resize(200, 200); drawer.show(); return app.exec(); } 

And after that I got nothing!
Could you tell me where I am wrong?

+6
c ++ qt
source share
3 answers

I think the problem is your QPainter initialization.

You could just create a QPainter response as in hydraulic systems, it would look like this:

 class PointDrawer: public QWidget { Q_OBJECT public: PointDrawer(QWidget* obj=0): QWidget(obj) {} virtual void paintEvent(QPaintEvent*) { QPainter p(this) p.setPen(QPen(Qt::black, 3)); int n = 8; while(...) { qreal fAngle = 2 * 3.14 * i / n; qreal x = 50 + cos(fAngle) * 40; qreal y = 50 + sin(fAngle) * 40; p.drawPoint(QPointF(x, y)); i++; } } } 

It can also use something like this, but I do not recommend it (I just prefer a different solution):

 class PointDrawer: public QWidget { Q_OBJECT private: QPainter p; public: PointDrawer(QWidget* obj=0): QWidget(obj) {} virtual void paintEvent(QPaintEvent*) { p.begin(this); p.setPen(QPen(Qt::black, 3)); int n = 8; while(...) { qreal fAngle = 2 * 3.14 * i / n; qreal x = 50 + cos(fAngle) * 40; qreal y = 50 + sin(fAngle) * 40; p.drawPoint(QPointF(x, y)); i++; } p.end(); } } 

In the second example, calls to QPainter::begin(this) and QPainter::end() needed. In the first example, you can think of QPainter::begin(this) called in the constructor, and QPainter::end() in the destructor

For this reason, I assume: Since QPaintDevice usually duplicated in QT4, QPainter::end() may be where the image is transferred to graphics memory.

+7
source share
 void SimpleExampleWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setPen(Qt::blue); painter.setFont(QFont("Arial", 30)); painter.drawText(rect(), Qt::AlignCenter, "Qt"); } 

http://doc.qt.digia.com/4.4/qpainter.html

+8
source share

You need to initialize the artist using the widget that you want to draw.
This is usually done using a constructor that accepts a QPaintDevice , but you can also do this by calling begin() .

0
source share

All Articles