Switching one widget to another in Qt

What is the best way to "swap" one QGraphicsWidget for another in its current form? I have a tree view widget and a shortcut widget, and I want them to occupy the same space at different times. In particular, when there is an error, I want to show it in the label, and when there is no error, I want to show the tree.

I tried programmatically hiding one and showing to others with hide() and show() , but the problem is that the hidden widget takes up space in my QGraphicsLinearLayout , even when it is hidden, leaving an empty space. Alternatively, I suppose I could add and remove widgets from the layout, but this seems difficult, as it involves changing the owner of the widget, and I will need to record their position in the layout so that I can insert them back in the right place.

In Java Swing, I would use CardLayout to achieve this, but I don't see the equivalent in Qt.

UPDATE: I discovered QStackedWidget . However, I work with QGraphicsScene , and therefore my widgets do not inherit from QWidget , but rather QGraphicsWidget , so I cannot add them to QStackedWidget .

+6
c ++ qt layout widget
source share
4 answers

How about a QStackedWidget ?

The QStackedWidget class provides a widget stack that displays only one widget at a time.

+2
source share

You can easily emulate QStackedWidget yourself. Create your own widget (whatever you want: from QWidget or from QGraphicsWidget and place it where you want two different widgets to appear. Put the widgets there and give it the ability to control which one is visible. Small work, you even can make it generic enough to be used as a QGraphicsWidget version of QStackedWidget .

+1
source share

There is something called QGraphicsAnchorLayout . You define "anchors" (the distance between the edges or corners of elements), so you can try to define the same anchors for your tree and label and hide widgets accordingly. Since both widgets will occupy the same area, there should be no spaces after hiding one element.

+1
source share

When you add a QWidget to a layout, the layout owner will not own the widgets. You must add your widget as a child of another QWidget for this (usually pass the parent in the constructor of the child).

Thus, removing a widget from lyout will remove it from the display behavior of the layout owner.

In your case, you can remove the widget from the layout and hide it. If you want to display it again, show it and add the widget to the layout. To insert it in the right place, you must save its place when you delete it.

Hope that helps

0
source share

All Articles