title: Qt Draw rectangle on Widget
body: <p>I need to draw rectangle on a widget which is child item of mainWindow. But the below code not succeed on drawing the Widget, it's drawing on parent screen.</p>
  
  <p><strong>mainwindow.cpp</strong></p>
  
  <pre><code>MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
      ui(new Ui::MainWindow)
  {
  
      ui-&gt;setupUi(this);
  }
  
  void MainWindow::paintEvent (QPaintEvent *e)
  {
   QPainter *painter = new QPainter (ui-&gt;widget);
   painter-&gt;begin (this);
   painter-&gt;drawRect(e-&gt;rect());
   painter-&gt;end ();
  }
  
  void MainWindow::mouseMoveEvent(QMouseEvent *event){
  
      update((QRect(LastPoint,event-&gt;pos())));
  }
  
  void MainWindow::mousePressEvent(QMouseEvent *event)
  {
      if (event-&gt;button() == Qt::LeftButton) {
          LastPoint = event-&gt;pos();
      }
  }
  
  MainWindow::~MainWindow()
  {
      delete ui;
  }
  </code></pre>
  
  <p><strong>mainwindow.hpp</strong></p>
  
  <pre><code>namespace Ui {
  class MainWindow;
  }
  
  class MainWindow : public QMainWindow
  {
      Q_OBJECT
  
  public:
      explicit MainWindow(QWidget *parent = 0);
      void paintEvent (QPaintEvent *e);
      void mouseMoveEvent(QMouseEvent *event);
      void mousePressEvent(QMouseEvent *event);
      QPoint LastPoint;
  
      ~MainWindow();
  
  private:
      Ui::MainWindow *ui;
  };
  </code></pre>
  
  <p>I have attached the screenshot of the designer. </p>
  
  <p><a href="https://i.stack.imgur.com/JdFwG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JdFwG.png" alt="enter image description here"></a></p>