Draw on QWidget

2020-05-08 06:58发布

问题:

How can I draw on QWidget(element on my form)?

I read many tutorials but none of them covers what I really have to do(draw some Rect on QWidget) .

I made a class MyFigure which inherits from QWidget, and at even paint wrote some code to draw a rectangle. Then, in my Form Create I create MyFigure object, and just show it.

IT DOESN"T WORK!!!

回答1:

QGraphicsView and QGraphicsScene are good for painting, but if you want to draw on QWidget you need to reimplement paintEvent:

#include <QWidget>
#include <QPainter>
#include <QPaintEvent>
class Widget : public QWidget
{
public:
    explicit Widget(QWidget *parent=0);

    void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
};

Widget::Widget(QWidget *parent) : QWidget(parent)
{
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter;
    painter.begin(this);
    painter.fillRect(event->rect(), Qt::white);
    QWidget::paintEvent(event);
    painter.end();
}

This code will fill your widget with white color.