QPainter painter object outside paintevent

自作多情 提交于 2020-01-24 20:57:25

问题


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:


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 ...
}


来源:https://stackoverflow.com/questions/18253980/qpainter-painter-object-outside-paintevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!