zoukankan      html  css  js  c++  java
  • QLayout及其子类 清除添加的widget

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

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

    而输出结果有些意外:

    11:21:42: Starting E:Qt_projcetplayuild-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debugdebugplay.exe...
    hlyCount == 5
    remove item  0
    remove item  1
    remove item  2
    remove item  3
    remove item  4
    hlyCount == 2
    11:21:58: E:/Qt_projcet/play/build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug/debug/play.exe exited with code 0

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

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

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

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

    运行结果:

    11:44:34: Starting E:Qt_projcetplayuild-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debugdebugplay.exe...
    hlyCount == 5
    remove item  4
    remove item  3
    remove item  2
    remove item  1
    remove item  0
    hlyCount == 0
    11:44:43: E:/Qt_projcet/play/build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug/debug/play.exe exited with code 0

    ok了

  • 相关阅读:
    adobe air ane 中有的java class 打包 apk 后却没有了报NoClassDefFoundError ,ClassNotFoundException
    厌烦了写findViewById 试试ButterKnife吧
    ios加载html5 audio标签用js无法自动播放
    一些css书写的小技巧
    canvas绘画基础(一):认识canvas画布
    H5新特性:video与audio的使用
    HTML5 进阶系列:文件上传下载
    h5移动端设备像素比dpr介绍
    HTML5 基础内容(元素/属性/格式化)
    前端如何将H5页面打包成本地app?
  • 原文地址:https://www.cnblogs.com/azbane/p/11617138.html
Copyright © 2011-2022 走看看