2
votes

I am trying to draw a simple two dimensional figure in a QWidget window. There is a paintEvent defined and a painter object of the QPainter class is also defined. My drawing contains elements which I need to draw more than once at various locations, such as lines, text etc. For this purpose, I am using functions to draw these lines with varying positions. Similarly for text. In order to make the program shorter, also modular.

The paintEvent function is calling functions which are used to calculate and draw.

How do I pass the QPainter painter object defined in the paintEvent into the functions.

for e.g.

void Classname::drawText(QString text, int PosX, int PosY, QPainter painter)
{
    QSize size=this->size();

    QFont times("Helvetica [Cronyx]", 10);
    QFontMetrics box(times);

    int boxWidth = box.width(text);
    int boxHeight = box.height();

    painter.setFont(times);
    painter.setPen(Qt::white);
    painter.drawText(PosX,PosY,text);
}

then I get an error where the vc++ environment is telling me that the typename is not allowed for the painter object of QPainter class.

If I define QPainter painter1 object as shown below:

void Classname::drawText(QString text, int PosX, int PosY, QPainter painter)
{
    QPainter painter1;

    QSize size=this->size();

    QFont times("Helvetica [Cronyx]", 10);
    QFontMetrics box(times);

    int boxWidth = box.width(text);
    int boxHeight = box.height();

    painter.setFont(times);
    painter.setPen(Qt::white);
    painter.drawText(PosX,PosY,text);
}

the program compiles but there is no output.

This is a part of the code, I am defining objects of the QPainter class in all the functions.

I read this thread, but the instructions are not clear. Must the begin() and end() function be called at all instances of drawing or just once in the paintEvent function?

1
I found out myself, the painter object can be passed as QPainter& painter. Then it works alright. - thedorkknight
You can also store painter "programs" inside a QPicture. You then simply replay it within your paintEvent. Another way is to use QPainterPath to store reusable, scalable vector graphics. - Kuba hasn't forgotten Monica

1 Answers

1
votes

As you mentioned you shall implement those functions in your class.

In your header:

class Class
{
// ...
protected:
    virtual void paintEvent( QPaintEvent* aEvent ) override;

private:
    void drawText( QPainter* aPainter, const QString& aText, int aPosX, int aPosY );
    // void drawLine( ... );
};

In your source:

void Class::paintEvent( QPaintEvent* aEvent )
{
    QPainter painter( this );

    // ...
    drawText( &painter/*, ... */ );
    drawLine( &painter/*, ... */ );
}

void Class::drawText( QPainter* aPainter, const QString& aText, int aPosX, int aPosY )
{
    // Your drawing ...
}