起初,我的思路是,先取得Layout的items数量, 然后通过索引来移除每一个items,代码如下:

    QHBoxLayout * hly = new QHBoxLayout;

    for(int i = ; i < ; i++)
{
QPushButton * btn = new QPushButton;
hly->addWidget(btn);
} int hlyCount = hly->count();
qDebug()<<"hlyCount =="<<hlyCount; for(int i = ; i < hlyCount; i++)
{
QLayoutItem * item = hly->itemAt(i);
hly->removeItem(item);
qDebug()<<"remove item "<<i;
} hlyCount = hly->count();
qDebug()<<"hlyCount =="<<hlyCount;

而输出结果有些意外:

::: Starting E:\Qt_projcet\play\build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug\debug\play.exe...
hlyCount ==
remove item
remove item
remove item
remove item
remove item
hlyCount ==
::: E:/Qt_projcet/play/build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug/debug/play.exe exited with code

查看Qt帮助手册有解释,itemAt()有三点值得关注:

-If there is no such item, the function must return
-如果子项不存在,返回零 -Items are numbered consecutively from
-item的排序从零开始 -If an item is deleted, other items will be renumbered.
-如果子项被删除,其他子项将被从新排序

哇~看到这里,知道了答案。下面看一下更改后的代码:

    QHBoxLayout * hly = new QHBoxLayout;

    for(int i = ; i < ; i++)
{
QPushButton * btn = new QPushButton;
hly->addWidget(btn);
} int hlyCount = hly->count();
qDebug()<<"hlyCount =="<<hlyCount; for(int i = hlyCount - ; i >= ; i--) //###改动:items编号,从大到小遍历
{
QLayoutItem * item = hly->itemAt(i);
if (item != nullptr) //###改动:判断子项是否存在
hly->removeItem(item);
qDebug()<<"remove item "<<i;
} hlyCount = hly->count();
qDebug()<<"hlyCount =="<<hlyCount;

运行结果:

::: Starting E:\Qt_projcet\play\build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug\debug\play.exe...
hlyCount ==
remove item
remove item
remove item
remove item
remove item
hlyCount ==
::: E:/Qt_projcet/play/build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug/debug/play.exe exited with code

ok了

最新文章

  1. 获取pe文件的文件类型
  2. 第一篇blog
  3. javascript平时例子⑩(表情发送)
  4. 启用CentOS6.5 64位安装时自带的MySQL数据库服务器
  5. Android double输出时保留两位小数
  6. 综合支撑【恶灵附身 Psycho Break】的世界观的概念艺术
  7. ZOJ 1240 IBM Minus One
  8. 牛一网ecshop综合类模板(仿淘常州) for ecshop 2.7.3
  9. 【Linux安全】防止 root 用户远程登录
  10. NOI2007 货币兑换
  11. Ironic中pxe driver和agent driver的区别
  12. 3、js无缝滚动轮播
  13. Vscode调试C的多文件工程配置
  14. 利用OpenCV给图像添加中文标注
  15. Jenkins+PowerShell持续集成环境搭建(一)前期准备
  16. Django中的Request和Response
  17. 一本通1639Biorhythms
  18. 如何修改 Ubuntu 的字符集?
  19. 最近编译tolua_runtime安卓编译错误
  20. npm audit fix

热门文章

  1. 正式开放 | 阿里云 10 亿级镜像服务正式支持 Helm Charts,云原生交付再加速!
  2. Kubernetes 部署集群内部DNS服务
  3. [Flutter] 转一个Flutter学习思维导图
  4. pytest-fixture参数化
  5. codeforces #592(Div.2)
  6. ORM:对象关系映射
  7. 【转】聊一聊-JAVA 泛型中的通配符 T,E,K,V,?
  8. Oracle 11g R2 Sample Schemas 安装
  9. Django框架(二十三)-- Django rest_framework-视图组件
  10. LCD RGB 控制技术讲解 — 时钟篇(上)【转】