【问题标题】:Qt remove Layout from other LayoutQt 从其他布局中删除布局
【发布时间】:2017-02-02 22:39:39
【问题描述】:

如何在运行时(按下按钮)从 layout_main 中删除 layout_newInfo?

我试过的代码:

    QLayout *layout = this->layout();

    QLayoutItem *item;
    while ((item = layout->takeAt(0)) != 0)
        layout->removeItem (item);
    delete layout_newInfo;
    layout_main->update();

【问题讨论】:

  • 显示您尝试过的代码。
  • 向 Qestien 添加了代码。
  • 请注意,while 循环中的调用 layout->removeItem (item); 不会执行任何操作,因为传递的 item 已被对 QLayout::takeAt 的调用删除。

标签: c++ qt qlayout


【解决方案1】:

您到底想实现什么? 如果要显示/隐藏现在位于 layout_newInfo 中的小部件,则 不要使用布局。使用放置在 layout_main(垂直布局)中的小部件,它本身具有 newInfo 项和布局,然后根据需要在小部件上使用 setVisible(true/false)。

【讨论】:

    【解决方案2】:

    如果 layout_newInfo 嵌套在 layout_main 中,如何在运行时从 layout_main 中删除 layout_newInfo?

    语义更清晰的方法:

    layout_main->removeItem(layout_newInfo); // make sure layout_newInfo object deleted
                                             // after either by parent or somehow else
    

    顺便说一句,通常这也应该删除嵌套布局:

    delete layout_newInfo; // also removes it from upper layout
    layout_main->update(); // triggers update on the screen
    

    因此,代码示例的最后两行就足够了,只有在没有触发其他更新时才需要调用 layout_main->update()

    here 的示例表明,删除 QLayout 的父级 QLayoutItem 也会将其从上部布局结构中删除(其析构函数会这样做)。

    【讨论】:

    • 这部分layout_main = new QVBoxLayout; layout_main->addLayout(layout_header); layout_main->addLayout(layout_data); layout_main->addLayout(layout_buttons); setLayout(layout_main); 在构造函数中。当点击按钮时出现这部分layout_main->addLayout(layout_newInfo);
    • 如果layout_newInfo 直接嵌套在layout_main 上,只需执行delete layout_newInfo 也可能是layout_main ->update()
    • 但随后出现了一些伪影。布局不会消失,它会悬停在其他布局上。
    • 调用了update()?在我看来,涉及的代码更多,但在简单的情况下,“悬停”不应该是这种情况。好的,брателло,工作要做。
    【解决方案3】:

    最后找到答案最好的方法是制作像void showNewInfo(QString action);这样的void方法

    在类cpp文件中

    void MainWind::showNewInfo(QString action)
    {
        if(action == "true")
        {
            bt_search->setEnabled(false);
            bt_production->setEnabled(false);
            bt_drying->setEnabled(false);
            bt_storage->setEnabled(false);
            ln_spent->show();
            cb_thickness1->show();
            cb_thickness2->show();
            cb_thickness3->show();
            cb_EFL1->show();
            cb_EFL2->show();
            bt_newItem->show();
        }
        else if(action == "false")
        {
            bt_search->setEnabled(true);
            bt_production->setEnabled(true);
            bt_drying->setEnabled(true);
            bt_storage->setEnabled(true);
            ln_spent->hide();
            cb_thickness1->hide();
            cb_thickness2->hide();
            cb_thickness3->hide();
            cb_EFL1->hide();
            cb_EFL2->hide();
            bt_newItem->hide();
        }
    }
    

    也可以使用setText(""),这样下次显示fragment就清楚了;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多