Reputation: 5452
I'm trying to write a GUI that paints a graph onto it in C++. I am getting a list of errors, all of which say: "QPainter::begin: Widget painting can onnly begin as a result of a paintEvent" Nothing appears to be painting.
#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();
}
#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
#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
Upvotes: 4
Views: 3137
Reputation: 73369
You're not doing widget painting correctly.
The proper thing way to do it is like 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 that is the only place you should be using QPainter. Then, whenever you want your widget to repaint itself, call update() on your widget, and Qt will call paintEvent() for you shortly afterwards.
Upvotes: 3
Reputation: 5496
From the Qt documentation:
Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent(); that is unless the Qt::WA_PaintOutsidePaintEvent widget attribute is set. On Mac OS X and Windows, you can only paint in a paintEvent() function regardless of this attribute's setting.
Upvotes: 4
Reputation: 22292
First, call show()
as suggested by Martin Beckett. Second, you cannot call paintEvent()
yourself. You need to override paintEvent()
and do your drawing there. Please see the example I provided in this answer.
Upvotes: 2
Reputation: 96177
You need to show the window
Window w;
w.show()
return app.exec();
Upvotes: 2