from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QOpenGLWidget from OpenGL.GL import * from OpenGL.GLU import * class GLWidget(QOpenGLWidget): def __init__(self, parent=None): super().__init__(parent) self.xRot = 20.0 self.yRot = 30.0 self.zRot = 0.0 self.rotation_speed = 2.0 self.timer = QTimer(self) self.timer.timeout.connect(self.updateRotation) def initializeGL(self): version = glGetString(GL_VERSION) print("GL version:", version) glClearColor(0.1, 0.1, 0.1, 1.0) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glEnable(GL_COLOR_MATERIAL) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) light_position = [4.0, 4.0, 8.0, 1.0] glLightfv(GL_LIGHT0, GL_POSITION, light_position) def resizeGL(self, w, h): if h == 0: h = 1 glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glLoadIdentity() gluPerspective(45.0, float(w) / float(h), 0.1, 100.0) glMatrixMode(GL_MODELVIEW) def paintGL(self): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glTranslatef(0.0, 0.0, -7.0) glRotatef(self.xRot, 1.0, 0.0, 0.0) glRotatef(self.yRot, 0.0, 1.0, 0.0) glRotatef(self.zRot, 0.0, 0.0, 1.0) self.drawCube() def drawCube(self): glBegin(GL_QUADS) # Front (red) glColor3f(1.0, 0.0, 0.0) glVertex3f(-1.0, -1.0, 1.0) glVertex3f( 1.0, -1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f(-1.0, 1.0, 1.0) # Back (green) glColor3f(0.0, 1.0, 0.0) glVertex3f(-1.0, -1.0, -1.0) glVertex3f(-1.0, 1.0, -1.0) glVertex3f( 1.0, 1.0, -1.0) glVertex3f( 1.0, -1.0, -1.0) # Top (blue) glColor3f(0.0, 0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0) glVertex3f(-1.0, 1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0) # Bottom (yellow) glColor3f(1.0, 1.0, 0.0) glVertex3f(-1.0, -1.0, -1.0) glVertex3f( 1.0, -1.0, -1.0) glVertex3f( 1.0, -1.0, 1.0) glVertex3f(-1.0, -1.0, 1.0) # Right (magenta) glColor3f(1.0, 0.0, 1.0) glVertex3f( 1.0, -1.0, -1.0) glVertex3f( 1.0, 1.0, -1.0) glVertex3f( 1.0, 1.0, 1.0) glVertex3f( 1.0, -1.0, 1.0) # Left (cyan) glColor3f(0.0, 1.0, 1.0) glVertex3f(-1.0, -1.0, -1.0) glVertex3f(-1.0, -1.0, 1.0) glVertex3f(-1.0, 1.0, 1.0) glVertex3f(-1.0, 1.0, -1.0) glEnd() def startRotation(self): if not self.timer.isActive(): self.timer.start(30) def stopRotation(self): if self.timer.isActive(): self.timer.stop() def resetView(self): self.xRot = 20.0 self.yRot = 30.0 self.zRot = 0.0 self.update() def updateRotation(self): self.xRot += self.rotation_speed self.yRot += self.rotation_speed * 0.8 self.zRot += self.rotation_speed * 0.5 self.update()