Displaying a custom graphics widget and adding as a dock widget

Hi.
I’ve coded a custom widget, which on its own, displays and works well. The widget inherits from QWidget. It’s made of a QGraphicScene which a bunch of clickable polygons are added to. In order to be able to render the scene, a QGraphicsView(scene) is needed. So it was added.

My problem was in viewing this widget. On its own I can display it with a show() (In the end of its defined Class, or at the running (“main”) section of the code).
But If I want it to be part of a QMainWindow (like being a QdockWidget), how do I get to be shown?
Do I have to use some sort of Layout (QHBoxLayout/QVBoxLayout) to be able to display it in the dock widget? or is there another way?

In fact, I can show the widget in the MainWindow using the QVBoxLayout, but:

  • extra scrolls are added to the edges of the widget which aren’t needed.
  • QHBoxLayout and QVBoxLayout require multiple widgets to be layed out. I have only one widget. So I’m thinking there probably should be another way.

Hi @mohsadeghi ,

Here is a simple example for using QDockWidget

# Dock widget
dock = QDockWidget("Dockable", main_window)
dock.setWidget(YourCustomWidget())
main_window.addDockWidget(Qt.RightDockWidgetArea, dock)

There are additional options for docking widgets, like the areas where the docking is allowed to be placed, features.

  • setAllowedAreas(areas) — Restrict which sides the dock can be placed (e.g., Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea).

  • setFeatures(features) — Set dock features .

  • setFloating(bool) — Make the dock float as a separate window.

  • isFloating() — Check if floating.

  • setTitleBarWidget(widget) — Custom title bar.

Also there is the useful property toggleViewAction returning an action that you can add into a QMenu or QToolbar (or both) for toggling the view of the dock view.