QPainter Error in GUI Application

I am trying to write a graphical interface that draws a graph on it in C ++. I get a list of errors, all of which say: "QPainter :: begin: drawing a widget can only begin as a result of paintEvent" It seems that nothing is being drawn.

main.cpp

#include <QApplication> #include <QFont> #include <QPushButton> #include <iostream> using namespace std; #include "skewNormal.h" #include "ui.h" int main(int argc, char* argv[]) { QApplication app(argc, argv); Window w; #if defined(Q_OS_SYMBIAN) w.showMaximized(); #else w.show(); #endif return app.exec(); } 

ui.h

 #ifndef UI_H_INCLUDED #define UI_H_INCLUDED #include <QtGui/QMainWindow> class Window : public QWidget { public: Window(); void paintEvent ( QPaintEvent * event ); }; #endif // UI_H_INCLUDED 

ui.cpp

 #ifndef GRAPHPN3670_H #define GRAPHPN3670_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QPaintEvent> #include <QtGui/QGraphicsView> #include <QtGui/QHeaderView> #include <QtGui/QMainWindow> #include <QtGui/QMenuBar> #include <QtGui/QStatusBar> #include <QtGui/QWidget> #include <QtCore/QRect> #include <iostream> using namespace std; #include "ui.h" #include "skewNormal.h" Window::Window() { cout<<"Hello1"; } void Window::paintEvent ( QPaintEvent * event ){ cout<<"Hello from paint event"; QPainter p(this); int xL = -width() / 2; int yL = 0; for(int x = -width() / 2; x < width() / 2; x++) { int y = getSkewNormal(0.5, x); p.drawLine(xL + width() / 2, height() - yL, x + width() / 2, height() - y); xL = x; yL = y; } } #endif // GRAPHPE3488_H 
+4
source share
4 answers

From the Qt documentation :

A warning. When the paint device is a widget, QPainter can only be used inside the paintEvent () function or in a function called by paintEvent (); what if the Widget Qt :: WA_PaintOutsidePaintEvent attribute is set. On Mac OS X and Windows, you can only paint in paintEvent () regardless of this attribute parameter.

+4
source

You are not drawing widgets correctly.

The correct way to do it is this:

 // Add this method to your widget class virtual void paintEvent(QPaintEvent * e) { QPainter p(this); // Add all calls to p.drawPoint(), etc here } 

... and this is the only place you should use QPainter. Then, whenever you want your widget to redraw itself, call update () on your widget, and Qt will soon call paintEvent () for you.

+3
source

You need to show the window

 Window w; w.show() return app.exec(); 
+2
source

Call show() , as Martin Becket suggested. Secondly, you cannot call paintEvent() yourself. You need to override paintEvent() and make a drawing there. See the example provided in this answer .

+2
source

All Articles