我在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_()
当前窗口的位置在中心和右下角之间,请参见图片:
如何在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_()
最佳答案
您必须将小部件移动到屏幕的中央,才能知道屏幕的大小,您必须使用QDesktopWidget
,如下所示:
app = QtWidgets.QApplication([])
window = QGLControllerWidget()
pos = QtWidgets.QDesktopWidget().rect().center() -window.rect().center()
window.move(pos)
window.show()
app.exec_()