【问题标题】:How to add a PyQtGraph to QMainWindow using QtWidgets?如何使用 QtWidgets 将 PyQtGraph 添加到 QMainWindow?
【发布时间】:2021-07-09 01:32:59
【问题描述】:

我正在使用 PyQt5 和 PyQtGraph。 我想把几个 QWidgets 放在一个 QMainWindow 中,包括一个 PlotWidget。以下代码确实显示了 QPushButton 和 QLabel,但不显示 PlotWidget。请告知如何修复代码以显示 PlotWidget。谢谢。

import sys
from PyQt5 import QtWidgets, QtCore
import pyqtgraph as pg
from pyqtgraph import PlotWidget, plot

# *********************************************************************************************

class MyGraph(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.plotWidget = pg.PlotWidget()
        # Add Axis Labels
        styles = {"color": "#f00", "font-size": "14px"}
        self.plotWidget.setLabel("left", "y-axis", **styles)
        self.plotWidget.setLabel("bottom", "x-axis", **styles)
        #self.plotWidget.setAutoVisible(y=True) # is this needed?
        # A lot more code goes here specific to my application, but removed from this example.
        # ...
        # end __init__

# *********************************************************************************************

class MyMainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("MyMainWindow")

        self.qButton = QtWidgets.QPushButton(self)
        self.qButton.setText("Button1")
        self.qButton.setGeometry(0, 0, 60, 30) # x, y, Width, Height

        self.qLabel = QtWidgets.QLabel(self)
        self.qLabel.setText("My Label Text Goes Here ... I want a PyQtGraph to be placed below.")
        self.qLabel.setGeometry(0, 40, 400, 20) # x, y, Width, Height
        
        self.qGraph = MyGraph()
        self.qGraph.setGeometry(0, 70, 500, 400) # x, y, Width, Height
        # end __init__

# *********************************************************************************************

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    w = MyMainWindow()
    w.resize(900,700)
    w.show()

    sys.exit(app.exec_())

【问题讨论】:

    标签: python pyqt5 pyqtgraph


    【解决方案1】:

    假设您想将 MyGraph 用作 PlotWidget 容器,那么首先要做的是通过布局设置小部件。另一方面,由于您不想在 MyMainWindow 中使用布局,因此 MyGraph 必须是 MyMainWindow 的子级,因此您必须将其作为父级传递。

    class MyGraph(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            self.plotWidget = pg.PlotWidget()
            # Add Axis Labels
            styles = {"color": "#f00", "font-size": "14px"}
            self.plotWidget.setLabel("left", "y-axis", **styles)
            self.plotWidget.setLabel("bottom", "x-axis", **styles)
    
            lay = QtWidgets.QVBoxLayout(self)
            lay.addWidget(self.plotWidget)
    
    self.qGraph = MyGraph(self)
    

    【讨论】:

      猜你喜欢
      • 2017-12-24
      • 2012-02-16
      • 1970-01-01
      • 2020-03-23
      • 2014-08-19
      • 2014-10-24
      • 2019-03-13
      • 2012-02-07
      • 2013-11-04
      相关资源
      最近更新 更多