Search code examples
pythonpyqtgraph

How do I get attributes from a pyqtgraph TextItem?


I'm using pyqtgraph and trying to recover the properties for my TextItem class objects added to a given graph.

Although it looks like it's a simple task, I can't figure out how to extract this and the documentation didn't help much.

Here's a snippet:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
import pyqtgraph as pg
import numpy as np

def refreshScreen(AnnotationsList):
        for i in range(len(AnnotationsList)):
              c = AnnotationsList[i]

              # Now I need to extract information from the annotations:
              x = c.x()
              print(x)

              y = c.y()
              print(y)

              text = c.text()
              print(text)

              OtherProperties = c.getProperty()
              print(OtherProperties)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()
    w.resize(250, 150)
    w.move(300, 300)
    w.setWindowTitle('Simple')
    w.show()

    AnnotationsList = []
    c = pg.TextItem(anchor=(0,0), border=pg.mkPen(200, 200, 200))
    c.setText(text='my_annotation', color=(0,0,0))
    # coordinates for annotation
    x = 5
    y = 10
    c.setPos(x,y)
    AnnotationsList = np.append(AnnotationsList, c)

    refreshScreen(AnnotationsList)

    sys.exit(app.exec_())

I guessed the .x() and .y() and got them right, but knowing how to extract other features would also be important! In the current form, it raises:

AttributeError: 'TextItem' object has no attribute 'text'

Solution

  • If you check the source code you see that TextItem has a QGraphicsTextItem that stores the information, so if you want to get the text information you should use that object:

    text = c.textItem.toPlainText()
    print(text)