0

So I currently have got a custom widget, and I want to add them to the main window after clicking a button. I would like to add them all to one fixed position first and then I will be able to drag them wherever I like. I am able to create and display these custom widgets with help of QHBoxLayout or QVBoxLayout, but in this case they will not be in the same position after I create them. Any help will be appreciated!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
stephen
  • 71
  • 8

1 Answers1

0

As the names suggest, the QLayout classes manage the position and geometry of the items added to them. You cannot move (eg. drag) an item out of a layout w/out first removing it from the layout (QLayout::removeItem() and derivatives). For example when you drag a toolbar or dock widget out of a QMainWindow it goes through all sorts of machinations to remove it from the MW layout, change the widget's window flags, remember the old position in the layout, and so on. And the reverse to dock it again.

To do what you describe (drag widgets arbitrarily around a window) you would need to not use a QLayout and position the widgets manually by specifying a QWidget::setGeometry() for example. After initial position, and assuming the user has some way to grab the widget (title bar or drag handle you made, etc), you'll probably still need to manage their positions, for example if the main window is resized (if you care about keeping them contained). Essentially you'd have a bunch of separate widgets acting as individual windows and probably need some way to keep track of them.

I don't know what kind of widgets you're talking about, but one option may be a QMdiArea which lets the user drag windowed widgets around, tabify them, save/restore state, and so on.

For more flexibility you could also look into the Qt Graphics Framework. The graphics scene has a lot of features for user-movable items/widgets, keeping track of them, and so on. It is probably the most flexible method overall, and you can also use regular QWidgets inside a graphics scene.

A couple other Q/A about arbitrarily positioning widgets (I'm sure there are more to be found):

Maxim Paperno
  • 4,485
  • 2
  • 18
  • 22
  • Hi, so for example my custom widget is to draw a rectangle but with some extra features to the MainWindow as RectangleWidget. After I click a button, a new RectangleWidget rw will be created, but I don't think call rw->setGeometry() will be able to display this widget, how can I do this? Thank you! – stephen Oct 17 '19 at 09:08
  • Hi @stephen, if the widget isn't visible by default, you simply call `QWidget::show()` on it (or `setVisible(true)`), either before or after positioning it with `setGeometry`. Your custom widget could also call `show()` from its constructor, for example. – Maxim Paperno Oct 17 '19 at 12:13