1

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)
Unfitacorn
  • 186
  • 2
  • 12

2 Answers2

4

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?

Mel
  • 5,837
  • 10
  • 37
  • 42
0

The other answer still holds, but since 0.13, QGraphicsWindow has been removed. You are supposed to use QGraphicsLayoutWidget instead.

Dear future me, (and dear other who might find this useful), please find below a working code sample to add a simple button to a graph.

import numpy as np

from pyqtgraph.Qt import QtWidgets, QtCore
import pyqtgraph as pg


def onButtonClicked():
    pg.plot(np.random.random(100))


win = pg.GraphicsLayoutWidget()

plot = win.addPlot()
# Or specify the position
# plot = win.addPlot(row=0, col=0)
plot.plot(np.random.random(100))

btn = QtWidgets.QPushButton("Show another graph")
btn.clicked.connect(onButtonClicked)
proxy = QtWidgets.QGraphicsProxyWidget()
proxy.setWidget(btn)
win.addItem(proxy)
# Or specify the position
# plot = win.addItem(proxy, row=0, col=0)

win.show()
pg.exec()
Eric Aya
  • 69,473
  • 35
  • 181
  • 253