Lefsler
Lefsler

Reputation: 1768

QPainter init painter and use it

I created a class called painter and created the QPainter p in the constructor passing the QMainWindow as a parameter.

So in the mainwindow.h i added:

protected:
    void paintEvent(QPaintEvent *e);

private:
    Ui::MainWindow *ui; // Created by the QT
    Painter* p;

In the mainwindow.cpp i added

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    p=new Painter(this);
}

and

void MainWindow::paintEvent(QPaintEvent *e)
{
    p->render(this);
}

Painter.h

#ifndef PAINTER_H
#define PAINTER_H
#include <QtCore>
#include <QtGui>

class Painter
{
private:
    QPainter* painter;
    bool init;

public:
    Painter(QMainWindow* m);
    ~Painter();

    void render(QMainWindow* m);
};

#endif // PAINTER_H

and painter.cpp

#include "painter.h"

Painter::Painter(QMainWindow* m)
{
    painter=new QPainter(m);
    //init=false;
}

void Painter::render(QMainWindow* m)
{
    painter->drawLine(10, 3,123, 909);
}

It doesn't draw a thing.

If i do

void Painter::render(QMainWindow* m)
{
    painer->begin(m);
    painter->drawLine(10, 3,123, 909);
}

It render the line and after 2-3 seconds it closes

The only way to make it work is to do

void Painter::render(QMainWindow* m)
{
    QPainter p(m);
    p.drawLine(10, 3,123, 909);
}

But it seems stupid initialize the p on every frame, it works like that. There's a way to just initialize the screen one time or make the begin work?

Thanks.

Upvotes: 2

Views: 2106

Answers (2)

Vincent Fourmond
Vincent Fourmond

Reputation: 3278

You are not using QPainter how it's meant to be. Essentially, a QPainter is meant to be created using

QPainter p(this);

inside the paint event handler. If you need, you can still pass the painter around using a pointer, but you're likely to hit problems like that if you use too many pointers to QPainter.

My understanding is that the painter gets initialized properly only when there's a paint event going on, which is why your initialization in Painter::Painter(QMainWindow* m) produces a non-functional QPainter.

Upvotes: 0

Lefsler
Lefsler

Reputation: 1768

Solved it with

painter->begin(this->m);
painter->drawLine(10, 2, 1232, 1222);
painter->end();

It seems stupid to me, but its better than declarate it on every frame. If someone have a better idea.

Thanks

Upvotes: 1

Related Questions