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_projcet\play\build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug\debug\play.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_projcet\play\build-play-Desktop_Qt_5_12_2_MinGW_64_bit-Debug\debug\play.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了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM