Qt - 清除所有的小部件从QWidget的布局 [英] Qt - Clear all widgets from inside a QWidget's layout

查看:1063
本文介绍了Qt - 清除所有的小部件从QWidget的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在对话框中有一个 QWidget 。在程序运行过程中,将几个 QCheckBox * 对象添加到布局中,如下所示:

I have a QWidget in a dialog. Over the course of the program running, several QCheckBox * objects are added to the layout like this:

QCheckBox *c = new QCheckBox("Checkbox text");
ui->myWidget->layout()->addWidget(c);

这适用于所有复选框。但是,我还有一个 QPushButton 在我的对话框中调用清除,当它被按下时应该将所有的东西从myWidget,留下空白, QCheckboxes 已添加。我一直在寻找在线和在文档,但我有麻烦找到一种方法来做到这一点。我发现了这个问题,我认为这个问题与我的问题类似,并尝试过他们的解决方案这个:

This works fine for all the checkboxes. However, I also have a QPushButton called "clear" in my dialog, which when it is pressed should empty everything out of myWidget, leaving it blank like it was before any of the QCheckboxes were added. I've been looking around online and in the docs but I am having trouble finding a way to do this. I found this question which I thought was similar to my problem, and tried their solution like this:

void myClass::on_clear_clicked()
{
  while(ui->myWidget->layout()->count() > 0)
  {
    QLayoutItem *item = ui->myWidget->layout()->takeAt(0);
    delete item;
  }
}

然而这似乎没有做任何事情。值得注意的是,我不知道这是否从他的答案翻译正确;它是有点不清楚如何应该实现的功能,所以我做了我最好的有根据的猜测。如果任何人知道我可以改变上述使它工作(或只是一个不同的方式,将工作),将非常感激。

This however did not seem to do anything. It's worth noting that I'm not sure if this is translated from his answer correctly; it was a bit unclear how the function given should be implemented, so I made my best educated guess. If anyone knows what I can change in the above to make it work (or just a different way that would work), it would be greatly appreciated.

推荐答案

布局的奇妙之处在于它们会自动处理一个窗口部件的删除。所以你真正需要的是迭代小部件,你完成了。因为你想擦除一个给定的小部件的所有孩子,只需:

The wonderful thing about layouts is that they handle a deletion of a widget automatically. So all you really need is to iterate over the widgets and you're done. Since you want to wipe out all children of a given widget, simply do:

foreach (QWidget * w, ui->myWidget::findChildren<QWidget*>()) delete w;

不需要担心布局。

如果你想要真的正确,你需要忽略的小部件是子部件,但是站在独立窗口。如果这是在通用的
库代码,这将是这种情况:

If you want to be really correct, you would need to ignore the widgets that are child widgets but are stand-alone windows. This would be the case if this was in general-purpose library code:

foreach (QWidget * w, ui->myWidget::findChildren<QWidget*>()) 
  if (! w->windowFlags() & Qt::Window) delete w;

这篇关于Qt - 清除所有的小部件从QWidget的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆