lte__
lte__

Reputation: 7586

Qt - reusable paint functions with custom arguments

I've been through a lot of material on the internet about this, but haven't found what I need. I want to make a reusable painting function in Qt. For example, I would have a

void paintRectangle(QPaintEvent*, int x, int y);

function, which I can call in a loop and draws a rectangle starting at the x and y coordinates. Is this possible? Could you please write down the draft/outline on how I should write it and how I can call it in the loop when it's ready? I really didn't find anything on this. Also, how would I call this function? What do I write in place of the QPaintEvent * when calling?

As I've noticed, paintevents get called before any class constructors. Is this correct? I'd like to have a certain amount of rectangles on the screen, which is depending on an n variable, which is being declared when a certain class gets instantiated. As of my current trials, it seemed that the n was undefined when my fuction tried to paint anything.

Upvotes: 0

Views: 588

Answers (1)

dtech
dtech

Reputation: 49309

The only limitation is that when you paint on widgets, it must happen in that widget's paint event. If your paint device is not a widget, then it doesn't matter.

Other than that, there is nothing preventing you from calling any number of painting functions any number of times with any parameters you'd want, just make sure that in the case of a widget, they are called in that widget's paint event. For example:

void paintEvent(QPaintEvent *) {
    QPainter p(this);
    // setup painter
    for (int i = 0; i < 200; i += 10) drawFoo(i, p);
}

void drawFoo(int i, QPainter & p) {
    p.drawPoint(i, i);
}

As I've noticed, paintevents get called before any class constructors. Is this correct?

Where did you notice that? I highly doubt a widget would be painted before it is constituted ;) Your concern is groundless, no widget is painted before it is constructed, in fact, you can construct a widget without painting it - if you don't call show(). If you put a debug message in the constructor and paint event, you will see that the constructor is always executed before the paint event. In fact, it would be entirely "illegal" to invoke a member function of an object which is not yet constructed fully.

Upvotes: 1

Related Questions