⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

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;


    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

    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));

Log in to reply