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

How to remove QLable which is added from example.cpp, not from example.ui of QT application.



  • Hi Team, I have added QLabel like below, in the example.cpp.

      void MainWindow::boxClicked()
     {
        if(Cb_Mag->isChecked())
             {
        QLabel *my_label = new QLabel(this);
        QRect crop_rect(200, 500, 250, 250);
        QImage desk = qApp->screens().at(0)->grabWindow(
        QDesktopWidget().winId(),
        crop_rect.left(),
        crop_rect.top(),
        crop_rect.width(),
        crop_rect.height()).toImage();
        my_label->show();
        my_label->setPixmap(QPixmap::fromImage(desk));
        my_label->setStyleSheet("border:5px solid grey");
        my_label->setGeometry(200, 500, 250, 250);
      }
     else
     {
        if (this->findChild<QLabel*>("my_label")) {
             // Here I want to remove the  my_label. 
           }
      }
    }
    

    In else block, I want to remove the code label called 'my_label'. any idea, please. Thank you.


  • Moderators

    The easiest would be to save the label pointer as a class member variable. This way you'd have instant access to it and could simply call delete on it.
    If you don't want to keep the variable around you can use findChild like you did, but you have to name the label first where you created it i.e.

    QLabel* my_label = new QLabel(this);
    my_label->setObjectName("my_label");
    ...
    

    and then you can delete it

    delete this->findChild<QLabel*>("my_label");
    
    


  • @chris I did as you suggested above 3 lines, still the label is not deleting.



  • @Chris-Kawa any other suggestion


  • Moderators

    This should work. You must've made a mistake somewhere. Can you show the code you wrote?

    Btw. unrelated to your question, but you do toImage() and in the next line QPixmap::fromImage(). It would be better to replace the QImage with QPixmap and avoid the extra conversions. They are pretty expensive.


  • Lifetime Qt Champion

    Hi,

    @NageswaRao said in How to remove QLable which is added from example.cpp, not from example.ui of QT application.:

    QLabel *my_label = new QLabel(this);

    If you added a member variable with the same name and kept this line as is, then it's normal it's not working because you are shadowing the member variable.



  • Thank you, @Chris Kawa and @SGaist . It's working, I did a mistake when I'm placing the delete related code.

    delete this->findChild<QLabel*>("my_label");

    I kept this in the wrong place, so it's not executing.


Log in to reply