Search code examples
c++qtqpainter

Qt Beginner: QPainter widget not rendering


I don't have much experience with Qt and I am having trouble using QPainter. I am trying to make a simple graphing widget which takes in a number of points and to create a QVector of QPoints, and then uses this vector to draw a polygon. However, nothing is appearing right now with my implementation. I am fairly certain that I have added the widget correctly to the window, as I can see the empty space it should occupy. This leads me to believe the problem to be in the graphing widget. Any assistance is appreciated.

header:

//graph.h

#ifndef GRAPH_H
#define GRAPH_H

#include <QWidget>
#include <QPainter>
#include <QVector>

class Graph : public QWidget
{
    Q_OBJECT

public:
    Graph(QWidget *parent = 0);
    QSize minimumSizeHint() const;
    QSize maximumSizeHint() const;
    QSize sizeHint() const;

    void addPoint(int w, int h);
    void clearPoints();
    void drawGraph();


protected:
    void paintEvent(QPaintEvent *event);


private:
    QPen pen;
    QBrush brush;
    QPixmap pixmap;
    QVector<QPoint> points;

};

#endif // GRAPH_H

source:

//graph.cpp

#include "graph.h"

Graph::Graph(QWidget *parent)
    : QWidget(parent)
{
    points.resize(0);

    setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);
}

void Graph::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setPen(QPen(Qt::NoPen));
    painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.drawPolygon(points);
}

QSize Graph::minimumSizeHint() const
{
    return sizeHint();
}

QSize Graph::maximumSizeHint() const
{
    return sizeHint();
}

QSize Graph::sizeHint() const
{
    return QSize(500, 200);
}

void Graph::addPoint(int w, int h)
{
    points.append(QPoint(w*2, h*2));
}

void Graph::clearPoints()
{
    points.clear();
}

void Graph::drawGraph() {
    points.prepend(QPoint(0,0)); //The base points of the graph
    points.append(QPoint(500,0));
    update();
    points.clear();
}

Solution

  • In drawGraph(), the call to update() posts an event notifying the widget to paint itself. You then clear the points and the drawGraph() call exits. After that, the event loop will process the update event and trigger a call to the paintEvent() but by then, there are no points in the vector of points to paint.

    Don't think of the paintEvent() as painting something permanent onto the widget once that will be displayed forever until you clear it and paint something else. The paintEvent() needs to be able to paint the widget from scratch whenever it needs to be redrawn. This is often due to a request from the system when the widget is moved, minimized and restored etc. This means your vector of points needs to remain until you no longer want a polygon to be displayed or the points are changed.