如何使用 QtWidgets 将 PyQtGraph 添加到 QMainWindow?

How to add a PyQtGraph to QMainWindow using QtWidgets?

我正在使用 PyQt5 和 PyQtGraph。 我想在 QMainWindow 中放置几个​​ QWidget,包括 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_())

假设您想将 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)