Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Draw with QPainter in a label



  • Hello, i want to know how can I draw a rectangle in a ui label, for exaple ui->label_2, Here is current code, but only draw in the window.

    void MainWindow::paintEvent(QPaintEvent *event){

    QPainter painter(this);
    
    QPen pen;
    pen.setColor(Qt::blue);
    painter.drawRect(QRect(80,120,200,100));
    

    }

    How Can I do to draw in ui->label_2 with QPainter????



  • @Isidro-Perla
    By (subclassing and overriding) your QLabel's paintEvent, instead of that of the MainWindow. Every QWidget has its own https://doc.qt.io/qt-5/qwidget.html#paintEvent.


  • Lifetime Qt Champion

    Hi
    You can also draw on a pixmap and then show that in the label.

    void MainWindow::on_pushButton_released() {
      int h = ui->label->height();
      int w = ui->label->width();
      QPixmap pix(w, h);
      QPainter paint(&pix);
      pix.fill( Qt::white );
      paint.setPen(QColor(0, 0, 0, 255));
      paint.drawRect(QRect(80,120,200,100));
      ui->label->setPixmap(pix);
    }
    

Log in to reply