使元素在PyQT5中的QScrollArea中水平拉伸

时间:2016-06-15 17:35:24

标签: python python-3.x pyqt pyqt5 qscrollarea

我正在使用Python 3.5PyQT5并尝试创建一个包含图表列表的窗口(使用matplotlib)。有足够的图表,窗口需要垂直滚动。

使用QScrollArea它会在两个方向上锁定图形大小,然后只是在窗口变小时滚动,这在我的用例中大多数情况下会导致右边的空格。只需使用基于QWidget的普通窗口,图表就可以适应。

理想情况下,我想找到一种方法让图形自然地水平拉伸以填充空间,并保持垂直固定以启用滚动。

这是一些简化的代码,它使一个窗口呈现拉伸行为,另一个呈现QScrollArea对象,两个方向都没有拉伸。

import sys
import matplotlib
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from PyQt5.QtWidgets import QWidget, QApplication, QScrollArea, QGridLayout, QSizePolicy


class SimpleGraph(FigureCanvas):
    """Canvas class, which acts as QWidget and renders a sin wave"""

    def __init__(self, parent=None, width=5, height=2, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        # We want the axes cleared every time plot() is called
        self.axes.hold(False)

        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)


class NormalWindow(QWidget):
    """Normal window based on Qwidget"""

    def __init__(self, width=480, height=320, title="Normal Window", *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setMinimumSize(width, height)
        self.setWindowTitle(title)
        self.show()

        grid = QGridLayout()
        grid.addWidget(SimpleGraph())
        grid.addWidget(SimpleGraph())
        grid.addWidget(SimpleGraph())

        self.setLayout(grid)


class ScrollWindow(QScrollArea):
    """Simple window based on QScrollArea"""
    def __init__(self):
        super().__init__()

        graph_list = QWidget()
        grid = QGridLayout()

        grid.addWidget(SimpleGraph())
        grid.addWidget(SimpleGraph())

        graph_list.setLayout(grid)

        self.setWidget(graph_list)

        self.setWindowTitle('Scroll Window')
        self.show()


app = QApplication(sys.argv)
window = NormalWindow()
window2 = ScrollWindow()
sys.exit(app.exec_())

0 个答案:

没有答案