1

Can I paint on a default QWidget in Qt on pressing a button or I have always create a subclass of QWidget and use its paintEvent() method?

mortalis
  • 2,060
  • 24
  • 34
  • `QWidget::paintEvent()` is a virtual function. You have to subclass to override it. Or maybe it worth to try the event filter approach. – vahancho May 28 '15 at 13:00
  • So I cannot draw a line directly on a QPushButton that I add to a form in QtCreator? – mortalis May 28 '15 at 13:13
  • I think no. But what prevents you from subclassing QPushButton? – vahancho May 28 '15 at 13:21
  • What you are trying to achieve? Don't ask how to do it with your idea, just describe from end user point of view what you want to change in this button. – Marek R May 28 '15 at 13:22
  • I wanted to know if there is a way to draw a line on a `QWidget` widget without creating a subclass. For example, by pressing a button I get the drawing context object `g` and call `g.drawLine(p1, p2)` and I get the line on the screen. – mortalis May 28 '15 at 19:02

1 Answers1

1

Without discussing the intention behind this design to allow common painting on all the widget without subclassing we can do:

class MyEventFilter : public QObject
{
public:
    MyEventFilter(QObject *parent = 0) : QObject(parent)
    {}

    bool eventFilter(QObject *obj, QEvent *e)
    {
        if (e->type() == QEvent::Paint)
        {
            QPaintEvent *ptrPaintEvent = static_cast<QPaintEvent *>(e);

            // depending on whether or not you want to have a default handling for this:
            // QObject::eventFilter(obj, e);
            // OR better to apply to specific event handler, pass widget as parent for this filter object for that 
            // static_cast<QWidget*>(parent())->paintEvent(ptrPaintEvent);

            // now do same thing as you would in paintEvent()
            return true;
        }
        // standard event processing
        return QObject::eventFilter(obj, e);
    }
};

// and attach it to just any widget
myWidget->installEventFilter(new MyEventFilter(myWidget));
Alexander V
  • 8,351
  • 4
  • 38
  • 47