2017-06-04 60 views
0

有一個示例程序PyQt5如何中心QGLWidget來繪圖的一個子類中PyQt5

我有一個類:

class QGLControllerWidget(QtOpenGL.QGLWidget): 
    ... 

而且主程序:

app = QtWidgets.QApplication([]) 
window = QGLControllerWidget() # this is my class 
window.show()      # I want to center the window on the screen 
app.exec_() 

當前窗口的位置在中心和右下角之間,請參閱圖像:

wrong-pos

如何中心在PyQt5屏幕上的窗口/小工具?

03_alpha_blending.py

import struct 

from PyQt5 import QtCore, QtOpenGL, QtWidgets 

import ModernGL 


class QGLControllerWidget(QtOpenGL.QGLWidget): 
    def __init__(self): 
     fmt = QtOpenGL.QGLFormat() 
     fmt.setVersion(3, 3) 
     fmt.setProfile(QtOpenGL.QGLFormat.CoreProfile) 
     fmt.setSampleBuffers(True) 
     self.timer = QtCore.QElapsedTimer() 
     super(QGLControllerWidget, self).__init__(fmt, None) 

    def initializeGL(self): 
     self.ctx = ModernGL.create_context() 

     prog = self.ctx.program([ 
      self.ctx.vertex_shader(''' 
       #version 330 

       in vec2 vert; 

       in vec4 vert_color; 
       out vec4 frag_color; 

       uniform vec2 scale; 
       uniform float rotation; 

       void main() { 
        frag_color = vert_color; 
        float r = rotation * (0.5 + gl_InstanceID * 0.05); 
        mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r)); 
        gl_Position = vec4((rot * vert) * scale, 0.0, 1.0); 
       } 
      '''), 
      self.ctx.fragment_shader(''' 
       #version 330 

       in vec4 frag_color; 
       out vec4 color; 

       void main() { 
        color = vec4(frag_color); 
       } 
      '''), 
     ]) 

     self.scale = prog.uniforms['scale'] 
     self.rotation = prog.uniforms['rotation'] 

     vbo = self.ctx.buffer(struct.pack(
      '18f', 
      1.0, 0.0, 1.0, 0.0, 0.0, 0.5, 
      -0.5, 0.86, 0.0, 1.0, 0.0, 0.5, 
      -0.5, -0.86, 0.0, 0.0, 1.0, 0.5, 
     )) 

     self.vao = self.ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color']) 

     self.timer.restart() 

    def paintGL(self): 
     self.ctx.viewport = (0, 0, self.width(), self.height()) 
     self.ctx.clear(0.9, 0.9, 0.9) 
     self.scale.value = (self.height()/self.width() * 0.75, 0.75) 
     self.rotation.value = self.timer.elapsed()/1000 
     self.ctx.enable(ModernGL.BLEND) 
     self.vao.render(instances=10) 
     self.ctx.finish() 
     self.update() 


app = QtWidgets.QApplication([]) 
window = QGLControllerWidget() 
window.show() 
app.exec_() 

回答

1

你必須到窗口小部件移動到屏幕的中心,要知道屏幕的尺寸則必須使用QDesktopWidget,如下所示:

app = QtWidgets.QApplication([]) 
window = QGLControllerWidget() 
pos = QtWidgets.QDesktopWidget().rect().center() -window.rect().center() 
window.move(pos) 
window.show() 
app.exec_() 
相關問題