我想在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关闭。
在此先感谢您的帮助。