0

I am trying to embed a FigureCanvasQTAgg, however when I do it it overlaps the top of the window where the close and resize buttons are located.

I am not sure why this behavior occurs.

PyQt window showing the problem described

Here is a code example that makes it easier to reproduce the problem:

import sys
import matplotlib; matplotlib.use("Qt5Agg")

from PyQt5 import QtWidgets, QtCore # <- additional import
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
from netgraph import EditableGraph


class MplCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        super(MplCanvas, self).__init__(Figure(figsize=(width, height), dpi=dpi))
        self.setParent(parent)
        self.ax = self.figure.add_subplot(111)
        self.graph = EditableGraph([(0, 1)], ax=self.ax)


class Dock(QtWidgets.QDockWidget):

    def __init__(self):
        super().__init__()

        self.canvas = MplCanvas(self, width=5, height=4, dpi=100)
        self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas.setFocus()

        self.toolbar = NavigationToolbar2QT(self.canvas, self)


        self.setFeatures(QtWidgets.QDockWidget.DockWidgetFloatable | QtWidgets.QDockWidget.DockWidgetMovable | QtWidgets.QDockWidget.DockWidgetClosable)

        aux = QtWidgets.QVBoxLayout()
        aux.addWidget(self.canvas)

        self.setLayout(aux)


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)


        widget = QtWidgets.QWidget()
        self.setCentralWidget(widget)

        layout = QtWidgets.QVBoxLayout(widget)

        self.dock = Dock()

        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)


def main():
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()


if __name__ == "__main__":
    main()

How do I make the FigureCanvasQTAgg fit only inside the DockWidget?

Lavínia Beghini
  • 165
  • 1
  • 11
  • 1
    QDockWidget is not a standard container, and has its own layout, so you must **not** try to set one and add a widget, but use [`setWidget()`](https://doc.qt.io/qt-5/qdockwidget.html#setWidget) instead. – musicamante May 04 '22 at 03:18
  • It worked! You can write it as an answer so I can mark it as resolved. – Lavínia Beghini May 04 '22 at 12:47

0 Answers0