Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 space 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.

like image 541
Rob H Avatar asked Mar 10 '10 18:03

Rob H


2 Answers

How about QStackedWidget?

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

like image 129
Ben Avatar answered Sep 25 '22 17:09

Ben


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.

like image 24
Caleb Huitt - cjhuitt Avatar answered Sep 24 '22 17:09

Caleb Huitt - cjhuitt