QLayout及其子类 清除添加的widget
2024-10-05 11:16:47
起初,我的思路是,先取得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了
最新文章
- 获取pe文件的文件类型
- 第一篇blog
- javascript平时例子⑩(表情发送)
- 启用CentOS6.5 64位安装时自带的MySQL数据库服务器
- Android double输出时保留两位小数
- 综合支撑【恶灵附身 Psycho Break】的世界观的概念艺术
- ZOJ 1240 IBM Minus One
- 牛一网ecshop综合类模板(仿淘常州) for ecshop 2.7.3
- 【Linux安全】防止 root 用户远程登录
- NOI2007 货币兑换
- Ironic中pxe driver和agent driver的区别
- 3、js无缝滚动轮播
- Vscode调试C的多文件工程配置
- 利用OpenCV给图像添加中文标注
- Jenkins+PowerShell持续集成环境搭建(一)前期准备
- Django中的Request和Response
- 一本通1639Biorhythms
- 如何修改 Ubuntu 的字符集?
- 最近编译tolua_runtime安卓编译错误
- npm audit fix
热门文章
- 正式开放 | 阿里云 10 亿级镜像服务正式支持 Helm Charts,云原生交付再加速!
- Kubernetes 部署集群内部DNS服务
- [Flutter] 转一个Flutter学习思维导图
- pytest-fixture参数化
- codeforces #592(Div.2)
- ORM:对象关系映射
- 【转】聊一聊-JAVA 泛型中的通配符 T,E,K,V,?
- Oracle 11g R2 Sample Schemas 安装
- Django框架(二十三)-- Django rest_framework-视图组件
- LCD RGB 控制技术讲解 — 时钟篇(上)【转】