I'm trying to understand the paintEvent function. What I want to do is to draw on top of a widget which contains different objects such as QLabel, QTextEdit, QPushButton or even other widgets. I made a quick example to demonstrate my wish. Consider the following code:

MyWidget.h
Qt Code:
  1. #ifndef MYWIDGET_H
  2. #define MYWIDGET_H
  3.  
  4. #include <QWidget>
  5. #include <QLabel>
  6. #include <QTextEdit>
  7.  
  8. class MyWidget : public QWidget
  9. {
  10. Q_OBJECT
  11. protected:
  12. void paintEvent(QPaintEvent *);
  13. public:
  14. MyWidget(QWidget *parent = 0);
  15. private:
  16. QLabel *label;
  17. };
  18.  
  19. #endif
To copy to clipboard, switch view to plain text mode 
MyWidget.cpp
Qt Code:
  1. #include <QVBoxLayout>
  2. #include <QPainter>
  3. #include "MyWidget.h"
  4.  
  5. MyWidget::MyWidget(QWidget *parent)
  6. : QWidget(parent)
  7. {
  8. QString text = "Some random text";
  9. label = new QLabel(text, this);
  10. label->setAlignment(Qt::AlignCenter);
  11. QVBoxLayout *vbox = new QVBoxLayout();
  12. vbox->addWidget(label);
  13. setLayout(vbox);
  14. }
  15.  
  16. void MyWidget::paintEvent(QPaintEvent *)
  17. {
  18. QPainter painter(this);
  19. painter.drawLine(100,50,300,50);
  20. }
To copy to clipboard, switch view to plain text mode 
main.cpp
Qt Code:
  1. #include <QApplication>
  2. #include "MyWidget.h"
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. QApplication app(argc, argv);
  7. MyWidget window;
  8. window.resize(400,400);
  9. window.show();
  10. return app.exec();
  11. }
To copy to clipboard, switch view to plain text mode 

This draws a line on my widget even if it contains a QLabel object.
Now, if I replace the QLabel with a QTextEdit covering the whole widget, the line is no longer visible. I guess the QTextEdit gets drawn on top of the line. What I'm wondering is if it's possible to force the widget to draw the line after the QTextEdit has been drawn? Or in general, is it possible to specify when a paintEvent shall occur? If this is impossible, what should I do if I want to draw on say a QTextEdit but still be able to write text?

Help much appreciated

Thanks!