开发者

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

   }


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?


Well, you need to create the variable on a scope accessible from all parts of the code where you want to access them. Most likely as private attributes of your window class.


From the code you posted, it looks like you want to replace the existing widget in a grid layout position. If that's the case , before adding the new widget to the position do this:

QLayoutItem * existingitem = ui->gridLayout->itemAtPosition(x, y);
if(existingitem) {
    ui->gridLayout->removeItem(existingitem);
    delete existingitem;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜