I'm making small python app for myself, but I've been stuck for days.
So I have simple non-resizeable GUI (PyQt5) and there is a live matplotlib chart inside a QVBoxLayout. I would like to remove this last layout and declare my gui layout free, but once I do, the chart disappears. Any help or advice is appreciated.

Here is a greatly shortened (working) version of my code:

Qt Code:
  1. import sys
  2. from random import randrange
  3. from PyQt5.QtWidgets import *
  4. from PyQt5.QtGui import *
  5. from PyQt5.QtCore import *
  6. from PyQt5 import QtCore
  7. import matplotlib
  8. import matplotlib.pyplot as plt
  9. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  10. from matplotlib.figure import Figure
  11. from threading import Thread
  12. from PyQt5 import QtTest
  13.  
  14. xdata = []
  15. ydata = []
  16.  
  17. def background_task():
  18. while True:
  19. global xdata
  20. global ydata
  21.  
  22. cp = randrange(10)
  23. ct = randrange(10)
  24.  
  25. if len(xdata) > 21:
  26. xdata = xdata[-21:]
  27. ydata = ydata[-21:]
  28. else:
  29. pass
  30.  
  31. xdata.append(str(cp))
  32. ydata.append(str(ct))
  33.  
  34. QtTest.QTest.qWait(1000)
  35.  
  36.  
  37. bg = Thread(target=background_task, daemon = True)
  38. bg.start()
  39.  
  40. class MplCanvas(FigureCanvas):
  41.  
  42. def __init__(self, parent=None, width=7, height=3, dpi=80):
  43. fig = plt.figure(figsize=(width, height), dpi=dpi)
  44. self.axes = fig.add_subplot(111)
  45. super(MplCanvas, self).__init__(fig)
  46.  
  47.  
  48. class MainWindow(QMainWindow):
  49.  
  50. def __init__(self, *args, **kwargs):
  51. super(MainWindow, self).__init__(*args, **kwargs)
  52. self.setFixedSize(600, 400)
  53.  
  54. self.canvas = MplCanvas(self, dpi=80)
  55. self.canvas.setFixedSize(QSize(600, 250))
  56. self.update_plot()
  57. self.timer = QtCore.QTimer()
  58. self.timer.setInterval(1000)
  59. self.timer.timeout.connect(self.update_plot)
  60. self.timer.start()
  61.  
  62. central_widget = QWidget()
  63. self.setCentralWidget(central_widget)
  64.  
  65. layout = QVBoxLayout(central_widget)
  66. layout.addWidget(self.canvas)
  67.  
  68. def update_plot(self):
  69. self.canvas.axes.cla()
  70. self.canvas.axes.plot(xdata, ydata, 'r')
  71. plt.xticks(rotation = 45)
  72. plt.tight_layout()
  73. every_nth = 3
  74. for n, label in enumerate(plt.gca().xaxis.get_ticklabels()):
  75. if n % every_nth != 0:
  76. label.set_visible(False)
  77. plt.tight_layout()
  78. self.canvas.draw()
  79.  
  80.  
  81. app = QApplication(sys.argv)
  82. window = MainWindow()
  83. window.show()
  84. sys.exit(app.exec_())
To copy to clipboard, switch view to plain text mode