You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PyQt5子布局中的Plotly图表随窗口自动调整大小

让PyQt5子布局里的Plotly图表随窗口自动缩放的解决办法

1. 给Web控件设置布局拉伸与大小策略

修改初始化代码,让QWebEngineView能占满布局的所有可用空间:

class MainWindow(QWidget, From_Main):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        
        self.browser = QtWebEngineWidgets.QWebEngineView(self)
        # 设置控件可在水平、垂直方向扩展
        self.browser.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # 添加到布局时设置拉伸因子,让它优先占据空间
        self.horizontalLayout_2.addWidget(self.browser, stretch=1)

2. 配置Plotly图表的响应式属性

在绘图时给图表加上自适应设置,同时调整HTML容器样式,确保图表填满Web控件:

def plotter(self):
    df_period = self.all_data.loc[:len(self.all_data)-13]
    df_predict = self.all_data.loc[len(self.all_data)-12:]
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df_period.index, y=df_period['value'], mode='lines', name='value'))
    fig.add_trace(go.Scatter(x=df_predict.index, y=df_predict['value'], mode='lines', opacity=0.7, name='value_true'))
    fig.add_trace(go.Scatter(x=df_predict.index, y=df_predict['value_predict'], mode='lines',  name='value_predict'))
    
    # 开启图表自动缩放,调整边距
    fig.update_layout(
        autosize=True,
        margin=dict(l=0, r=0, t=30, b=0),
        responsive=True
    )
    
    # 生成带样式的HTML,确保容器占满控件空间
    base_html = fig.to_html(include_plotlyjs='cdn')
    full_html = f"""
    <html>
        <head>
            <style>
                body, html {{
                    margin: 0;
                    padding: 0;
                    width: 100%;
                    height: 100%;
                }}
                .plotly-graph-div {{
                    width: 100% !important;
                    height: 100% !important;
                }}
            </style>
        </head>
        <body>
            {base_html}
        </body>
    </html>
    """
    self.browser.setHtml(full_html)

3. 检查.ui文件的布局设置

确保horizontalLayout_2的属性符合要求:

  • 布局的sizePolicy设为水平、垂直方向都可扩展
  • 如果布局里还有其他控件,不要给它们设置过高的拉伸因子,避免抢占图表的空间
  • 父窗口/容器的大小策略也要设为可扩展,保证窗口缩放时布局能跟着调整

内容的提问来源于stack exchange,提问作者catauggie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:25:18