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

PyQt6页面切换失效与实时图表过小问题求助

PyQt6应用问题修复:页面切换失效+图表尺寸偏小

问题1:页面切换功能完全失效

原因:侧边栏按钮仅绑定了标签文本修改逻辑,未触发QStackedWidget的页面切换操作。
修复:给按钮添加切换stackedWidget当前页面的代码,绑定对应页面索引。

问题2:图表尺寸异常偏小

原因:pyqtgraph.PlotWidget作为graphicsView子控件时,未通过布局管理填充父控件空间,导致使用默认小尺寸显示。
修复:给graphicsView设置布局,将PlotWidget加入布局,使其自动填充整个父控件区域。


修复后的完整逻辑代码

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout
from PyQt6.QtCore import QTimer
import pyqtgraph as pg
from untdwdfd import Ui_MainWindow


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 绑定按钮与页面切换逻辑
        self.pushButton.clicked.connect(self.switch_to_page1)
        self.pushButton_3.clicked.connect(self.switch_to_page2)
        self.pushButton_2.clicked.connect(self.switch_to_page3)
        
        # 修复图表尺寸:给graphicsView添加布局
        layout = QVBoxLayout(self.graphicsView)
        layout.setContentsMargins(0, 0, 0, 0)
        self.graphWidget = pg.PlotWidget()
        layout.addWidget(self.graphWidget)
        
        self.graphWidget.setBackground('w')
        self.graphWidget.setXRange(0, 10, padding=0)
        self.graphWidget.setYRange(0, 10, padding=0)
        self.data = [0] * 10
        self.curve = self.graphWidget.plot(self.data, pen='b')
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.update_graph)
        self.is_graph_running = False

    def switch_to_page1(self):
        self.stackedWidget.setCurrentIndex(0)
        # 保留图表启停逻辑
        self.is_graph_running = not self.is_graph_running
        if self.is_graph_running:
            self.pushButton.setText("Stop Graph")
            self.timer.start()
        else:
            self.pushButton.setText("Start Graph")
            self.timer.stop()

    def switch_to_page2(self):
        self.stackedWidget.setCurrentIndex(1)
        self.label_2.setText("it is empty here")

    def switch_to_page3(self):
        self.stackedWidget.setCurrentIndex(2)
        self.label_3.setText("here is still empty")

    def update_graph(self):
        self.data.pop(0)
        self.data.append(pg.QtCore.QTime.currentTime().msec() / 1000)
        self.curve.setData(self.data)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:10:10