Reputation: 45
I am using PyQt5 and PyQtGraph. I would like to put several QWidgets in a QMainWindow, including a PlotWidget. The following code does display the QPushButton and the QLabel, but does not display the PlotWidget. Please advise on how to fix the code so that the PlotWidget is displayed. Thanks.
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_())
Upvotes: 1
Views: 1311
Reputation: 243887
Assuming you want to use MyGraph as a PlotWidget container then the first thing to do is set the widget through a layout. On the other hand, since you don't want to use layouts in MyMainWindow then MyGraph must be a child of MyMainWindow so you must pass it as parent.
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)
Upvotes: 1