我正在尝试将小部件大小调整为数字大小。由于某种原因,画布和小部件的大小不会改变。我试图设置容器小部件和画布的SizePolicy,结果相同。
import sys
import matplotlib.pyplot as plt
from PyQt4 import QtGui
class CanvasOnWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self._layout = QtGui.QVBoxLayout(self)
self._fig = plt.figure()
self._layout.addWidget(self._fig.canvas)
plt.plot(range(10),range(10))
self._fig.canvas.mpl_connect('button_press_event', self._resize)
def _resize(self, event):
w,h = self._fig.get_size_inches()
if event.button == 1: # left click
h-=1
elif event.button == 3: # right click
h+=1
self._fig.set_size_inches(w, h, forward=True)
self._fig.canvas.draw()
self._fig.canvas.flush_events()
print self.size()
print self._fig.canvas.size()
print self._fig.get_size_inches()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = CanvasOnWidget()
main.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
我猜你需要通知小部件你想要改变它的大小。
这可以使用.resize
完成。由于画布周围有边框,因此在设置新窗口小部件时需要考虑此边框。
import sys
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt4 import QtGui
class CanvasOnWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self._layout = QtGui.QVBoxLayout(self)
self.setLayout(self._layout)
self._fig = Figure()
self.canv = FigureCanvas(self._fig)
self._layout.addWidget(self.canv)
ax = self._fig.add_subplot(111)
ax.plot(range(10),range(10))
self._fig.canvas.mpl_connect('button_press_event', self._resize)
def _resize(self, event):
w,h = self._fig.get_size_inches()
dw = self.size().width()-w*self._fig.dpi
dh = self.size().height()-h*self._fig.dpi
if event.button == 1: # left click
h-=1
elif event.button == 3: # right click
h+=1
self._fig.set_size_inches(w, h, forward=True)
self._fig.canvas.draw_idle()
self.resize(w*100+dw,h*100+dh)
print self.size()
print self._fig.canvas.size()
print self._fig.get_size_inches()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = CanvasOnWidget()
main.show()
sys.exit(app.exec_())
请注意,我已更改为代码,以便将Figure
放入FigureCanvasQT
。在Qt GUI中使用pyplot会导致问题。
但是,如果你想使用pyplot,整个代码可以简化很多。
import matplotlib.pyplot as plt
class Plot():
def __init__(self):
self._fig = plt.figure()
ax = self._fig.add_subplot(111)
ax.plot(range(10),range(10))
self._fig.canvas.mpl_connect('button_press_event', self._resize)
def _resize(self, event):
w,h = self._fig.get_size_inches()
if event.button == 1: # left click
h-=1
elif event.button == 3: # right click
h+=1
self._fig.set_size_inches(w, h, forward=True)
self._fig.canvas.draw_idle()
print self._fig.get_size_inches()
if __name__ == '__main__':
app = Plot()
plt.show()