In this article, we will build a simple 3D modeling and animation app using Python. We will use PyQt for the GUI and PyOpenGL to render and rotate a 3D cube. This beginner-friendly guide walks you through the entire setup step-by-step.
Installation
Install the required libraries using pip:
pip install PyOpenGL PyQt5
PyOpenGL: Python bindings for OpenGL, used to draw and render 3D geometry.
PyQt5: GUI toolkit used to create the application window, layouts and controls.
Now let’s look at the step-by-step implementation of this app.
Step by step Implementation
Step 1: Import the Required Libraries
Before starting the app, we import everything needed for GUI creation, OpenGL rendering, and math calculations.
Explanation:
QMainWindow, QApplication, QVBoxLayout, QWidget, QPushButton: provide the main window, event loop, vertical layout, widget container, and a button for the GUI.
QGLWidget: supplies an OpenGL surface inside a Qt widget where we render OpenGL content.
from OpenGL.GL import *: brings in OpenGL drawing and state functions such as glBegin, glVertex3f, glRotatef, etc.
math: used here for math helpers (e.g., math.tan, math.radians) when setting the projection.
sys: used to read command-line args and to exit the application cleanly.
Step 2: Create the Main Application Window
Here we create the window, add the OpenGL widget and a button for future actions.
Explanation
setGeometry(...) sets the window position and size
setWindowTitle(...) sets the title, the layout and central widget arrange child widgets
GLWidget() is added as the OpenGL drawing area
The button is wired to create_object() for later use.
Step 3: Initialize OpenGL Settings
Now we prepare the OpenGL environment by setting a background color and enabling depth testing so the cube looks properly 3D.
Explanation:
glClearColor(...) sets the background color to black
glEnable(GL_DEPTH_TEST) enables depth testing so nearer fragments hide farther ones.
Step 4: Adjust Projection When Window Resizes
Whenever the window size changes, we update the camera view so the cube stays proportionate.
Explanation:
glViewport(...) sets the drawable region
glFrustum(...) constructs a perspective projection based on field-of-view and aspect ratio
switching back to GL_MODELVIEW prepares OpenGL for drawing objects.
Step 5: Draw and Animate a Rotating 3D Cube
This method clears the frame, sets camera transforms, draws six faces as quads, and increments the rotation for animation.
Explanation:
glClear(...) clears color and depth buffers
glTranslatef(...) moves the scene back so the cube is visible