Reputation: 1
I want to make a Qt application draw an Ellipse (a circle). I’m using a two file setup - main.cpp
and ui_mainwindow.h
. I have defined a QGraphicsView
and a QPainter
on the Ui MainWindow
class:
class Ui MainWindow {
public:
...
QGraphicsView *radarGraphicsView;
QPainter *radarPainter;
...
I have as well initialized the QGraphicsView:
void setupUi(QMainWindow *MainWindow) {
...
radarGraphicsView = new QGraphicsView(centralWidget);
...
I have defined a paintEvent in the same class as well:
void paintEvent(QPaintEvent *event) {
radarPainter = new QPainter(radarGraphicsView);
radarPainter->setPen(Qt::green);
radarPainter->drawEllipse(10, 10, 10, 10); }
Anyways, in result I cannot see any ellipse being drawn in the QGraphicsView, and I assume I’m supposed to call the paintEvent, but I’ve found no such example in a setup like mine (Qmake). How am I supposed to call the paintEvent for the Ellipse to be drawn?
Upvotes: 0
Views: 2452
Reputation: 1262
void paintEvent(QPaintEvent*) override;
is a virtual member function of QWidget
class and it's used to draw on widgets derived from QWidget
. In case you want to draw an ellipse into QWidget
you have to override that like following.
class MyClass : public DerivedFromQWidget
{
...
protected: // or any other
void paintEvent(QPaintEvent* event){
QPainter painter(this);
painter.setPen(Qt::black);
painter.setBrush(Qt::red);
painter.drawEllipse(ellipse);
...
DerivedFromQWidget::paintEvent(event);
}
...
};
The paintEvent
function will be called continuous while it's implementer is shown.
I believe the following class can help you to solve the problem
// ellipse_drawer.h
class EllipseDrawer : public QWidget
{
public:
EllipseDrawer(QWidget* parent = nullptr);
protected:
void paintEvent(QPaintEvent*);
};
// ellipse_drawer.cpp
EllipseDrawer::EllipseDrawer(QWidget* parent)
: QWidget(parent)
{
setFixedSize(200, 200);
}
void EllipseDrawer::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setPen(Qt::black);
painter.setBrush(Qt::red);
painter.drawEllipse(rect());
}
// my_main_window.h
class MyMainWindow : QMainWindow
{
MyMainWindow(QWidget* parent = nullptr);
};
// my_main_window.cpp
MyMainWindow::MyMainWindow(QWidgat* parent)
: QMainWindow(parent)
{
setCentralWidget(new EllipseDrawer());
}
// in main.cpp
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyMainWindow widget;
widget.show();
return app.exec();
}
Upvotes: 2