Search code examples
pythonuser-interfacepyqtpyqtgraph

How do I add a QPushButton to PyQtGraph using addItem?


I am trying to add a button at the bottom of two plots that will display data to read in from a file. Underneath these two plots will be a button to control an action. I have attempted to add a widget, layout, graphicsItem from the pyqt library. I can easily add a label to the layout but when adding a button I get the following error

addItem(self, QGraphicsLayoutItem, int, int, alignment: Union[Qt.Alignment, Qt.AlignmentFlag] = Qt.Alignment()): argument 1 has unexpected type 'QPushButton'

The code being tested:

import pyqtgraph as pg

win = pg.GraphicsWindow()

win.setWindowTitle('Test App')
label = pg.LabelItem(justify='right')
win.addItem(label)

button = QtGui.QPushButton()

p1 = win.addPlot(row=0, col=0)
p2 = win.addPlot(row=1, col=0)
p3 = win.addLayout(row=2, col=0)
p3.addItem(button,row=1,col=1)

Solution

  • The pyqtgraph documentation on addItem states that it "adds a graphics item to the view box."

    The thing is, a QtPushButton is not a graphic item, it's a widget. Therefore the error: addItem is expecting a QGraphicsLayoutItem (or something that inherits that class), and you're passing a QWidget

    To add a widget into a GraphicsWindow, you could wrap it with QGraphicsProxyWidget

    proxy = QtGui.QGraphicsProxyWidget()
    button = QtGui.QPushButton('button')
    proxy.setWidget(button)
    
    p3 = win.addLayout(row=2, col=0)
    p3.addItem(proxy,row=1,col=1)
    

    But depending on what you need to do, you might want to implement a PyQt GUI, with the GraphicsWindow being one element of this GUI. This question could help you: How to update a realtime plot and use buttons to interact in pyqtgraph?