pyqt 使用openglwidget导入obj模型
时间: 2023-05-15 10:07:17 浏览: 109
可以使用 PyOpenGL 库来加载和渲染 OBJ 模型,然后将其嵌入到 PyQt 的 OpenGLWidget 中。以下是一个简单的示例代码:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QOpenGLWidget
from PyQt5.QtGui import QOpenGLShader, QOpenGLShaderProgram
from PyQt5.QtCore import QFile, QTextStream
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import sys
class MyGLWidget(QOpenGLWidget):
def __init__(self, parent=None):
super(MyGLWidget, self).__init__(parent)
def initializeGL(self):
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
self.loadObj('model.obj')
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0)
glPushMatrix()
glRotatef(30, 1, 0, 0)
glRotatef(60, 0, 1, 0)
glCallList(self.obj.gl_list)
glPopMatrix()
def resizeGL(self, w, h):
glViewport(0, 0, w, h)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45.0, w / h, 0.1, 100.0)
def loadObj(self, filename):
self.obj = OBJ(filename, swapyz=True)
class OBJ:
def __init__(self, filename, swapyz=False):
self.vertices = []
self.normals = []
self.texcoords = []
self.faces = []
material = None
for line in open(filename, "r"):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'v':
v = list(map(float, values[1:4]))
if swapyz:
v = [v[0], v[2], -v[1]]
self.vertices.append(v)
elif values[0] == 'vn':
v = list(map(float, values[1:4]))
if swapyz:
v = [v[0], v[2], -v[1]]
self.normals.append(v)
elif values[0] == 'vt':
self.texcoords.append(list(map(float, values[1:3])))
elif values[0] in ('usemtl', 'usemat'):
material = values[1]
elif values[0] == 'f':
face = []
texcoords = []
norms = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
texcoords.append(int(w[1]))
else:
texcoords.append(0)
if len(w) >= 3 and len(w[2]) > 0:
norms.append(int(w[2]))
else:
norms.append(0)
self.faces.append((face, norms, texcoords, material))
self.gl_list = glGenLists(1)
glNewList(self.gl_list, GL_COMPILE)
glEnable(GL_TEXTURE_2D)
glFrontFace(GL_CCW)
for face in self.faces:
vertices, normals, texture_coords, material = face
if material is not None:
# TODO: use materials
pass
glBegin(GL_POLYGON)
for i in range(len(vertices)):
if normals[i] > 0:
glNormal3fv(self.normals[normals[i] - 1])
if texture_coords[i] > 0:
glTexCoord2fv(self.texcoords[texture_coords[i] - 1])
glVertex3fv(self.vertices[vertices[i] - 1])
glEnd()
glDisable(GL_TEXTURE_2D)
glEndList()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
widget = MyGLWidget(window)
window.setCentralWidget(widget)
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
```
这个例子使用 PyOpenGL 加载和渲染 OBJ 模型,并将其嵌入到 PyQt 的 OpenGLWidget 中。你可以将 `loadObj` 函数中的 `filename` 参数替换为你要加载的 OBJ 模型的文件名。
阅读全文