在PySide中將QDeclarativeView變成使用OpenGL來渲染

假設你已經有一個使用QDeclarativeView的程式,你覺得顯示效能始終不夠滿意。如何才能增進程式的效能了?讓我們看看下面這個簡單的程式。

[][1]

from PySide.QtCore import *  
from PySide.QtGui import *  
from PySide.QtDeclarative import *  

class MyView(QDeclarativeView):  
 def __init__(self, src):  
 super(MyView, self).__init__()  
 self.setAttribute(Qt.WA_TranslucentBackground)  
 self.viewport().setAutoFillBackground(False)  
 self.setWindowTitle('My QML Windows')  
 self.setSource(src)  
 self.setResizeMode(QDeclarativeView.SizeRootObjectToView)  

app = QApplication([])  
view = MyView(src="MyView.qml")  
view.show()  
app.exec_()  

其實,需要的工作遠比你想像的容易。只要稍作修改,就可以透過OpenGL來加速程式了!

from PySide.QtCore import *  
from PySide.QtGui import *  
from PySide.QtOpenGL import *  
from PySide.QtDeclarative import *  

class MyView(QDeclarativeView):  
 def __init__(self, src, useOpenGL=False):  
 super(MyView, self).__init__()  
 if useOpenGL:  
 format = QGLFormat.defaultFormat()  
 format.setSampleBuffers(False)   
 glw = QGLWidget(format)  
 glw.setAutoFillBackground(False)  
 self.setViewport(glw)  
 self.setAttribute(Qt.WA_TranslucentBackground)  
 self.viewport().setAutoFillBackground(False)   
 self.setWindowTitle('My QML Windows')  
 self.setSource(src)  
 self.setResizeMode(QDeclarativeView.SizeRootObjectToView)   

app = QApplication([])  
view = MyView(src="MyView.qml", useOpenGL=True)  
view.show()  
app.exec_()  

[1]:

comments powered by Disqus