简体   繁体   中英

Remove QLayoutItem from a Layout, but still use it later on?

Here is the environment first: I have a self defined "Property Editor" which is a QGroupBox (derives from QWidget) Currently I have a class let's call it "Holder", which has a reference to two of the Property Editors.

Now I have multiple "Holder" classes and one vertical QVBoxLayout (called Sidebar). In this layout I want both of the Property Editors of the currently selected Holder class to be displayed.

And there is the issue: When the user selects another holder class, I want the Property Editors of the previously selected Holder class to disappear, and add the Property Editors of the new selected Holder class.

Selecting another Holder class works once. But when I select the first Holder class again, The editors don't seem to change. Why? Does "takeAt(..)" destroy the reference in the holder class? How can I get the desired behavior?

Here is the code, thanks in advance:

void App::setSelection(Holder * holder){
    if(m_currentlySelected == holder) return;

    m_viewer->sideBarRemoveAt(0);
    m_viewer->sideBarInsertAt(0, holder->firstPropEditor);
    m_viewer->sideBarRemoveAt(1);
    m_viewer->sideBarInsertAt(1, holder->secondPropEditor);

    m_currentlySelected = holder;
}

void QtViewer::sideBarRemoveAt(int i){
    m_sideBar->m_layout->takeAt(i);
}

void QtViewer::sideBarInsertAt(int i, QWidget * widget){
    m_sideBar->m_layout->insertWidget(i, widget);
}

QLayout::takeAt() doesn't remove the widget of the QLayoutItem from its parent widget. The only reason it may seem to work the first time is probably because the other widgets were above (z-index wise) the first ones.

Rather than playing with the layout, you could

  • just hide/show your 2 PropertyEditor whenever the holder changes, hidden items don't generate holes in the layout, the next visible item is displayed as if the hidden items were not part of the layout, or
  • use a QStackedWidget to stack all the PropertyEditor at the same place and select which one is displayed (with QStackedWidget::setCurrentIndex() ).

Does "takeAt(..)" destroy the reference in the holder class?

No, this method removes the QLayoutItem from the layout. See reference page for takeAt . This class doesn't release the layout item (it is your responsibility to do).

But when I select the first Holder class again, The editors don't seem to change. Why?

I am not quite clear what you are trying to achieve (not enough code in your example), but if you are trying to change the layout using QLayoutItem's, then it is the simplest to create new layout and add items you want to display to it. Or simply, remove all items from the layout, and add the items that should be visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM