开发者

Swapping one widget with another in Qt

What is the best way to "swap" one QGraphicsWidget with another in an existing view? I have a tree view widget and a label widget, and I want them to occupy the same space at different times. Specifically, when there's an error, I want to show it in the label, and when there's no error, I want to show the tree.

I have tried programmatically hiding one and showing the other with hide() and show(), but the problem is that the hidden widget occupies spac开发者_如何学运维e in my QGraphicsLinearLayout even when it's hidden, leaving an empty gap. Alternatively, I suppose I could add and remove the widgets from the layout, but that seems heavy-handed since it implies a change in ownership of the widgets and I'd need to record their position in the layout so I could insert them back in the right place.

In Java Swing, I'd use a CardLayout to achieve this, but I don't see an equivalent in Qt.

UPDATE: I discovered QStackedWidget. However, I am working with a QGraphicsScene and so my widgets don't inherit from QWidget but rather QGraphicsWidget, so I can't add them to a QStackedWidget.


How about QStackedWidget?

The QStackedWidget class provides a stack of widgets where only one widget is visible at a time.


You can fairly easily emulate a QStackedWidget on your own. Create your own widget (however you want to, either from QWidget or from QGraphicsWidget and put it where you want the two different widgets to appear. Put your widgets in there, and allow it to control which one is visible. With a little work, you could even make it generic enough to be used as a QGraphicsWidget version of QStackedWidget.


There is something called QGraphicsAnchorLayout. You define "anchors" (the distances between edges or corners of items), so you can try defining the same anchors for your tree and label and hiding the widgets appropriately. Since both widgets will occupy the same area, there should be no gap after hiding one item.


When you add a QWidget to a layout, the layout's owner will not take ownership of your widget. You have to add your widget as child of an other QWidget for that (Generally pass the parent in the constructor of the child).

So removing a widget from the lyout will only remove it from the display behaviour of the layout's 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 at the right place you have to save its place when removing it.

Hope that helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜