Reputation: 833
I have a custom widget, which inherits QWidget. It has own paintEvent and I cannot change it. So I want to use such a widget in my dialog object, but I need to draw some graphics on it after it draws its own graphics (that widget draws video frames on it, an I need to draw some lines over it). Can I draw every time after the paintEvent of that widget? I used installEventFilter and caught the event wuth type Qt::Paint, but I canoont see anything I've drown. Is there any other way?
Upvotes: 1
Views: 6110
Reputation: 98425
You can derive from the custom widget class, reimplement paintEvent
, and call the inherited paintEvent
first, then do your drawing.
You can install an event filter on the widget and do the same: call the widget's paintEvent
first, then do your drawing.
Hide the other widget. Create your own widget, and call the other widget's render
method in your widget's paintEvent
, then do your drawing. Since the other widget is presumably rendering video frames that change periodically over time, you might need to use a timer to update()
your widget.
In neither case are you modifying the 3rd party custom widget.
In order to call other widget's protected paintEvent
you need to be using a QWidget
, even if just a dummy, invisible one.
Upvotes: 3
Reputation: 439
This is a very simple code sample that draw inside a custom widget. It draws a blue rectangle inside of a QPushButton.
The method used is exactly what has been described in option 1 by @Kuba
So, you inherit from the custom widget class where you want to draw in, reimplement paintEvent
, and call the inherited paintEvent
first and the do your drawing.
Hope this helps
#include <QApplication>
#include <QPushButton>
#include <QPainter>
#include <QPaintEvent>
// inherit from the class over which you want to draw
class DrawOverButton : public QPushButton
{
Q_OBJECT
public:
DrawOverButton(const QString &text, QWidget *parent = 0) :
QPushButton(text, parent)
{
// enlarge the button so there is some space to draw in
setStyleSheet("QPushButton {min-height: 60px; "
"min-width: 120px; margin: 5px;}");
}
protected:
virtual void paintEvent(QPaintEvent *event) {
// call the base class paint event method
// this will draw the base class content
QPushButton::paintEvent(event);
// draw a blue border inside the button
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(QColor("#3cf"), 4));
const int distance = 20;
painter.drawRoundedRect(QRect(distance, distance,
width() - 2 * distance, height() - 2 * distance),
10, 10);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DrawOverButton *button = new DrawOverButton("Button");
button->show();
return a.exec();
}
#include "main.moc"
Upvotes: 3