Search code examples
python-2.7openglpyqt2dpyopengl

How to pan and zoom vertex lines in QtOpenGL


I'm looking for a way to move some lines form by glVertex but so far I have no solid solution for it, here's my code. I've tried moving glOrtho, it does not work, I've tired adding translation, it does not work if I panning constantly. And I have no idea what to do with zoom too, perhaps I should create a camera and turn it into a full 3D scene? But I'm not finding good documentation for that so I hope someone can shed me some light, thanks.

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
from PyQt4 import QtGui, QtCore
from PyQt4.QtOpenGL import *


class SampleWidget(QGLWidget):
    xTranslationChanged = QtCore.pyqtSignal(int)
    yTranslationChanged = QtCore.pyqtSignal(int)

    def __init__(self, parent=None):
        super(SampleWidget, self).__init__(parent)
        self.xTrans = 0
        self.yTrans = 0
        self.w = 1600
        self.h = 900
        self.lastPos = QtCore.QPoint()
        self.v_pos = [[50, 50], [75, 100], [100, 150], [200, 200], [300, 250], [400, 450]]

    def paintGL(self):
        glClear(GL_COLOR_BUFFER_BIT)
        glBegin(GL_LINE_STRIP)
        glColor3f(1.0, 0.0, 0.0)
        for i, x in enumerate(self.v_pos):
            if i < len(self.v_pos) - 1:
                glVertex2i(self.v_pos[i][0], self.v_pos[i][1])
                glVertex2i(self.v_pos[i + 1][0], self.v_pos[i + 1][1])
        glEnd()

    def resizeGL(self, w, h):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, 1600, 0, 900, -1.0, 1.0)
        #glViewport(0, 0, w, h)

    def initializeGL(self):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

    def mousePressEvent(self, event):
        self.lastPos = event.pos()

    def mouseMoveEvent(self, event):
        dx = event.x() - self.lastPos.x()
        dy = event.y() - self.lastPos.y()
        # self.xTranslate(dx)
        # self.yTranslate(dy)
        glViewport(dx, dy, dx + 1600, dy + 900)
        if event.buttons() & QtCore.Qt.RightButton:
            pass

    def xTranslate(self, dx):
        self.xTrans = dx
        self.xTranslationChanged.emit(dx)
        self.updateGL()

    def yTranslate(self, dy):
        self.yTrans = -dy
        self.yTranslationChanged.emit(dy)
        self.updateGL()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    widget = SampleWidget()
    widget.show()
    app.exec_()

Solution

  • There should be a glTranslate in there somewhere to move the lines you are rendering to the right position. You should set the matrix mode to GL_MODELVIEW before calling glTranslate.

    You can do zooming using glScale.