我想在QML應用程序中編寫自定義OpenGL Widget,以使用MathGL繪製數據。
要做到這一點,我看了一下場景圖示例http://doc.qt.io/qt-5/qtquick-scenegraph-openglunderqml-example.html
然後我調整了代碼以滿足我的需要,然後出現問題,圖像只閃爍一個渲染週期,之後不再出現。 以下是重要的功能和綁定。使用QOpenGL函數渲染問題
類GLRenderEngine:公共QObject的,公共QOpenGLFunctions
void GLRenderEngine::render()
{
if(!m_bInit)
{
initializeOpenGLFunctions();
m_pGraph = new mglGraph(1);
m_bInit = true;
}
glViewport(m_Viewport.left(), m_Viewport.top(), m_Viewport.width(), m_Viewport.height());
m_pGraph->Clf();
//Graph stuff ...
m_pGraph->Finish();
if(m_pWindow)
m_pWindow->resetOpenGLState();
}
類GLWidget:公共QQuickItem
GLWidget::GLWidget(QQuickItem *parent) : QQuickItem(parent)
{
m_pRender = 0;
connect(this, &QQuickItem::windowChanged, this, &GLWidget::handleWindowChanged);
}
void GLWidget::handleWindowChanged(QQuickWindow *win)
{
if(win)
{
connect(win, &QQuickWindow::beforeSynchronizing, this, &GLWidget::sync, Qt::DirectConnection);
connect(win, &QQuickWindow::sceneGraphInvalidated, this, &GLWidget::cleanup, Qt::DirectConnection);
win->setClearBeforeRendering(false);
}
}
void GLWidget::cleanup()
{
if(m_pRender)
{
delete m_pRender;
m_pRender = 0;
}
}
void GLWidget::sync()
{
if(!m_pRender)
{
m_pRender = new GLRenderEngine();
connect(window(), &QQuickWindow::beforeRendering, m_pRender, &GLRenderEngine::render, Qt::DirectConnection);
}
m_pRender->setViewportSize(boundingRect());
m_pRender->setWindow(window());
}
QML-文件
import QtQuick 2.8
import QtQuick.Window 2.2
import GLWidget 1.0
Window {
visible: true
width: 320
height: 480
GLWidget{
anchors.fill: parent
id: glView
}
Rectangle {
color: Qt.rgba(1, 1, 1, 0.7)
radius: 10
border.width: 1
border.color: "white"
anchors.fill: label
anchors.margins: -10
}
Text {
id: label
color: "black"
wrapMode: Text.WordWrap
text: "The background here is a squircle rendered with raw OpenGL using the 'beforeRender()' signal in QQuickWindow. This text label and its border is rendered using QML"
anchors.right: parent.right
anchors.left: parent.left
anchors.bottom: parent.bottom
anchors.margins: 20
}
}
我也注意到,當我用QQuickFramebufferObject圖像消失在調用update()或窗口的resize事件之後,即使渲染函數被調用,也是如此,所以我的猜測是緩衝區沒有被更新,或者其他的qt關閉。
在此先感謝您的幫助。