Search code examples
pythonpyqt4pyqtgraph

How to align the center of a textwidget in pyqtgraph


I would like to use a textwidget to display a text over an image, and make sure that the text is centered in the image. (I actually want to make a movie where the text changes with every frame to indicate what was changed).

I tried the following (in a jupyter notebook):

%pylab inline
%gui qt
import pyqtgraph as pg
 
# new cell
imv = pg.ImageView()
imv.show()

#new cell
# add a textwidget
tw_center = pg.TextItem('')
tw_center.setFont(pg.Qt.QtGui.QFont("arial", 20))
imv.addItem(tw_center)
# set it in the center
tw_center.setPos(50, 0)
# display text in red to make it visible
tw_center.setText('hi there', (255,0,0))

# create and show data
data = np.random.rand(100,100)
imv.setImage(data)

However, this results in a non-centered text label as the left corner is currently in the center. How do I get the center of the text in the center of the image? The size of my data might change, as well as the text in the textwidget, so I'm looking for a more clever way than just trial and error. I looked at the setAnchor method but it only specifies the corners.


Solution

  • It looks like you need to set the anchor right. If you look at the documentation, you can see that you could initiate the TextItem with a different anchor. To get it centered, you might need something like

    tw_center = pg.TextItem('',anchor=(0.5,0))
    

    This will set the item's anchor to be centered in x-direction.