Search code examples
c++qtqwidget

How to access widgets created within functions in later function calls in Qt


So currently I have code, in C++, that creates a few QLabels, a QLineEdit, and a QCheckBox when a selection is made from a QComboBox. However, I would like to be able to access the widgets I have created in a later function to destroy them if a new selection is made from the combo box. I am able to access the objects created from using the Designer by doing ui->Object but i am not able to do that with objects created by using my own code. Can I do that some how, because I know how to work with that.

In short, I would like to be able to dynamically create/destroy QWidgets based on selections made by the user. Is there a reference I should know of to do this, or any documentation? Or am I just completely going about this the wrong way? Here is the code I presently have for creating the objects:

   if (eventType == QString::fromStdString("Birthday"))
   {

   QLabel *label1 = new QLabel ("Celebrant: ");
   QLabel *label2 = new QLabel ("Surprise: ");
   QLineEdit *lineEdit = new QLineEdit;
   QCheckBox *box = new QCheckBox;

   ui->gridLayout->addWidget(label1,3,0,1,1, 0);
   ui->gridLayout->addWidget(label2,4,0,1,1,0);
   ui->gridLayout->addWidget(lineEdit,3,1,1,1,0);
   ui->gridLayout->addWidget(box,4,1,1,2,0);

   }

Solution

  • If you give them names (using setObjectName()) you can find them later using QObject::findChildren().

    But wouldn't it be easier just to store them in member variables?