Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 781
Unfitacorn Avatar asked Dec 12 '25 05:12

Unfitacorn


2 Answers

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?

like image 197
Mel Avatar answered Dec 14 '25 18:12

Mel


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()
like image 43
Aurélien Cibrario Avatar answered Dec 14 '25 17:12

Aurélien Cibrario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!