cozimus77
cozimus77

Reputation: 23

Pyqt application using matplotlib plots strange behavior when used in a different monitor

I'm creating a Pyqt application where i want to plot an empty figure when the application is loaded, and then plot some data every time a button is pressed.

Here is my current minumum working example:

import matplotlib.pyplot as plt
from random import random
from PyQt6 import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg


class Window(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(1126, 568)
        self.centralwidget = QtWidgets.QWidget()
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.pushButtonConnect = QtWidgets.QPushButton("Connect")
        self.gridLayout.addWidget(self.pushButtonConnect, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)
        self.fig, self.ax = plt.subplots()
        self.canvas = FigureCanvasQTAgg(self.fig)
        self.gridLayout.addWidget(self.canvas, 0, 1, 1, 1)
        self.pushButtonConnect.clicked.connect(self.runGraph)
        self.ax.set_xlim([0, 1])
        self.ax.set_ylim([0, 1])

    def runGraph(self):
        canvas_new = FigureCanvasQTAgg(self.fig)
        plt.plot([random(), random()], [random(), random()])
        self.gridLayout.replaceWidget(self.canvas, canvas_new)
        self.canvas = canvas_new


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    win = Window()
    win.show()
    app.exec()

Which gives an application that, after 5 button clicks looks like this.

However if a open the same application on my laptop screen (rather than in my external monitor), every time I click the button every line get bigger, and after 5 clicks looks like this.

And even more: If I try to resize the main Window with:

self.resize(1126, 568)

on my monitor looks normal after 5 clicks, but on my laptop screen it looks like this, like it's resizing the grid if I click the button.

I'm doing something wrong or it's a bug of matplotlib+Pyqt?

Thank you very much in advance.

Upvotes: 0

Views: 76

Answers (1)

cozimus77
cozimus77

Reputation: 23

As relent95 suggested in the comment, simply using self.canvas.draw() does the job and fix the issue. So now the function is:

def runGraph(self):
    plt.plot([random(), random()], [random(), random()])
    self.canvas.draw()

On the other hand, the mystery of my laptop strange behaviour will stay unsolved.

Upvotes: 0

Related Questions