Solved Performing QPainter outside paintEvent(QPaintEvent* event)
-
Hi everyone, I wanted to place the QPainter outside QPaintEvent because I want it to paint only once. If I were to place QPainter in the QPaintEvent, upon update(), I afraid it will continuously paint again and again when I place a variable inside paintEvent. This will ram up the CPU usage which is kind of unncessary. Is there any way or example to paint outside QPaintEvent?
I tried putting it in a an empty function but it doesnt work.
Here is my code for reference. Thank you and looking forward for a discussion.//paint_circle.h
//paint_circle.h #ifndef PAINT_CIRCLE_H #define PAINT_CIRCLE_H #include <QMainWindow> #include <QPainter> #include <QPaintEvent> namespace Ui { class paint_circle; } class paint_circle : public QMainWindow { Q_OBJECT public: explicit paint_circle(QWidget *parent = 0); ~paint_circle(); QSize sizeHint() const { return rect.size(); } protected: void paintEvent(QPaintEvent* event); private: Ui::paint_circle *ui; QRect rect; void paint_test(); }; #endif // PAINT_CIRCLE_H
//paint_circle.cpp
//paint_circle.cpp #include "paint_circle.h" #include "ui_paint_circle.h" paint_circle::paint_circle(QWidget *parent) : QMainWindow(parent), ui(new Ui::paint_circle) { ui->setupUi(this); rect = QRect(0, 0, this->width(), this->height()); paint_test(); } paint_circle::~paint_circle() { delete ui; } void paint_circle::paint_test(){ //I WANT TO TRANSFER LAYER 1 BACKGROUND DRAWING HERE. } void paint_circle::paintEvent(QPaintEvent* event) { //BACKGROUND DRAWING (LAYER 1) QRectF rectangle(0, 0, this->width(), this->height()); QPainter b_color(this); b_color.setPen(QPen(Qt::white,0 )); b_color.fillRect(event->rect(), Qt::transparent); b_color.setBrush(QColor(Qt::red)); b_color.drawRoundedRect(rectangle, 20.0, 10.0); //TO REMAIN HERE (LAYER 2) QPainter p(this); p.setRenderHint(QPainter::Antialiasing, true); p.setPen(QPen(Qt::white, 0)); p.setBrush(Qt::black); p.drawEllipse(QRect((this->width()/2)-15,(this->height()/2)-15,30,30)); p.rotate(90); // some random rotation number. }
-
@Faruq No, you can only paint on a widget inside paintEvent.
Also what is the point to paint only once? After next update() your painting will be lost.
If your painting is static you can paint onto a QPixmap once and then, in your paintEvent, you just paint that pixmap. -
@jsulm Thank you!
-
If you must do something only once then that is a prime use of a static local variable:
void method() { static bool first(true); if (first) { do_stuff(); first = false; } }