如何在 Qt 中的后续函数调用中访问在函数内创建的小部件
所以目前我有 C++ 代码,当从 QComboBox 中进行选择时,它会创建一些 QLabels、QLineEdit 和 QCheckBox。但是,我希望能够访问我在后面的函数中创建的小部件,以便在从组合框中进行新选择时销毁它们。我可以通过执行 ui->Object 来访问使用设计器创建的对象,但我无法使用我自己的代码创建的对象来执行此操作。我能以某种方式做到这一点吗,因为我知道如何处理它。
简而言之,我希望能够根据用户的选择动态创建/销毁 QWidget。是否有我应该知道的参考资料或任何文档?或者我只是完全以错误的方式处理这件事?这是我目前用于创建对象的代码:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您给它们命名(使用
setObjectName()
),您可以稍后使用QObject::findChildren()
找到它们。但是将它们存储在成员变量中不是更容易吗?
If you give them names (using
setObjectName()
) you can find them later usingQObject::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: