0
目標是使用OpenGL和Pyqt5繪製一條線(如MS繪圖中)。 問題是我得到的只是一個黑色的窗口。如果glRectf(20,20,-20,20)
這樣的東西寫在paintGL()
中,它顯示正確。 代碼 -QGLWidget不更新(Pyqt5和OpenGL)
from OpenGL.GL import *
from PyQt5.QtOpenGL import *
from PyQt5.QtCore import QTimer
a = b = None
class Coordinate():
def __init__(self,x,y):
self.x = x/2 -200 # mapping x [0,800] to [-200,200]
self.y = -2*y/3 + 200 # mapping y [0,600] to [200,-200]
def getx(self):
return self.x
def gety(self):
return self.y
class GlWindow(QGLWidget):
def __init__(self):
print("Entering GL")
super(GlWindow,self).__init__()
self.setAutoBufferSwap(True)
# timer = QTimer()
# timer.timeout.connect(self.update)
# timer.start(10)
def mousePressEvent(self,e):
a = Coordinate(e.x(),e.y())
print(a.getx(),a.gety())
def mouseMoveEvent(self,e):
b = Coordinate(e.x(),e.y())
print(b.getx(),b.gety())
self.updateGL()
def mouseReleaseEvent(self,e):
b = Coordinate(e.x(),e.y())
print(b.getx(),b.gety())
self.updateGL()
def paintGL(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glColor3f(0.0,0.0,1.0)
if a and b is not None:
print("Drawing line")
glBegin(GL_LINES)
glVertex2f(a.getx(),a.gety())
glVertex2f(b.getx(),b.gety())
glEnd()
def resizeGL(self, w, h):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-200, 200, -200, 200, -200.0, 200.0)
glViewport(0, 0, w, h)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def initializeGL(self):
glClearColor(0.10, 0.10, 0.10, 1.0) # Grey
glClearDepth(1.0)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glShadeModel(GL_SMOOTH)
標準輸出 -
Entering GL
66.5 40.0
66.5 40.0
66.5 40.66666666666666
67.0 40.66666666666666
67.5 40.66666666666666
69.0 42.0
70.5 42.66666666666666
72.5 44.66666666666666
74.0 46.0
75.5 46.66666666666666
76.5 48.0
77.5 48.66666666666666
78.5 49.33333333333334
79.0 49.33333333333334
79.0 49.33333333333334
79.5 49.33333333333334
79.5 49.33333333333334
79.5 49.33333333333334
的GlWindow()實例在另一小窗口創建(主窗口:QMainWindow的,用於菜單條),並設置爲中央部件。我嘗試Qtimer和更新(),它沒有工作。
而你100%確定'resizeGL'在'paintGL'之前總是被調用至少一次? – genpfault
是的,以及我所做的是我添加了2個打印語句(「在resizeGL」,「在paintGL」),並且都被打印出來。而且每次mousevent發生時,都會打印「在paintGL」語句中。所以updateGL工作?對不起,我是一個新手:) –
[This answer](https://stackoverflow.com/a/46259752/2588654)我在這裏寫的應該在PyQt4(而不是5)窗口畫一個三角形到屏幕上。唯一奇怪的是,爲什麼要經歷將座標映射到奇數glOrtho矩陣而不是利用寬度和高度的麻煩?我有一種感覺,即繪畫正在發生,但也許線條不是在窗口的視圖中繪製的。 – CodeSurgeon