Search code examples
python-3.xpyqtgraphpyqt6qtopengl

How to add labels to 3D Axis in pyqtgraph


I would like to add labels to a 3D axis drawn in GLViewWidget from pyqtgraph.opengl. I followed the example but did not manage to make it work properly. When I subclass the GLViewWidget object and overwrite the paintGL() method, it says that there are not any self.qglColor and self.renderText attributes inherited from the parent ('MyGLView' object has no attribute 'qglColor'; 'MyGLView' object has no attribute 'renderText').

Here is the code:

from pyqtgraph.opengl import GLViewWidget
from PyQt6.QtGui import QFont, QColor, QFontMetrics
from PyQt6.QtWidgets import QApplication


class MyGLView(GLViewWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

    def paintGL(self, *args, **kwargs):
        GLViewWidget.paintGL(self, *args, **kwargs)

        font = QFont()
        font.setFamily("Tahoma")
        font.setPixelSize(21)
        font.setBold(True)

        title_str = 'Screen Coordinates'
        metrics = QFontMetrics(font)
        m = metrics.boundingRect(title_str)
        width = m.width()
        height = m.height()

        scrn_sz_width = self.size().width()

        self.qglColor(QColor(255, 255, 0, 255))
        self.renderText((scrn_sz_width-width)/2, height+5, title_str, font)


app = QApplication([])
fig1 = MyGLView()
fig1.show()

Any suggestion whether I am just using wrong version (0.13.3) of pyqtgraph? If that is the case can I just make it work without downgrading/upgrading?


Solution

  • You have to use QPainter to paint in paintGL method.

    Here is an example you can use:

    from pyqtgraph.opengl import GLViewWidget
    from PyQt6.QtGui import QFont, QColor, QFontMetrics, QPainter, QPen
    from PyQt6.QtWidgets import QApplication
    
    
    class MyGLView(GLViewWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
        def paintGL(self, *args, **kwargs):
            GLViewWidget.paintGL(self, *args, **kwargs)
    
            painter = QPainter(self)
    
            font = QFont()
            font.setFamily("Tahoma")
            font.setPixelSize(21)
            font.setBold(True)
            painter.setPen(QPen(QColor(255, 255, 0, 255)))
            painter.setFont(font)
    
            title_str = 'Screen Coordinates'
            metrics = QFontMetrics(font)
            m = metrics.boundingRect(title_str)
            width = m.width()
            height = m.height()
    
            scrn_sz_width = self.size().width()
            painter.drawText(int((scrn_sz_width - width) / 2), height + 5, width, height, 0, title_str)
            painter.end()
    
    
    app = QApplication([])
    fig1 = MyGLView()
    fig1.show()
    app.exec()