首页 文章

Qt qml应用程序下的OpenGL场景

提问于
浏览
2

这应该是如何将自定义opengl添加到qml应用程序的最佳方法 .

http://qt-project.org/doc/qt-5/qtquick-scenegraph-openglunderqml-example.html

问题是,我不想画整个窗口,但只是在我的opengl自定义qt快速项目占用的矩形 . 我想我可以用适当的参数调用glViewport,所以opengl会绘制我项目的矩形 .

实际上,这对我不起作用 .

qml:

import QtQuick 2.2
import QtQuick.Controls 1.1
import ge.components 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    color: "red"

    menuBar: MenuBar {
        Menu {
            title: qsTr("Filxe")
            MenuItem {
                text: qsTr("Exit")
                onTriggered: Qt.quit();
            }
        }
    }

    GLViewer {
        width: 200
        height: 200
        x: 100
        y: 100
    }
}

qt quick item: 在paint方法中,我首先使用ApplicationWindow的颜色填充整个窗口,然后我想用黑色填充我的项目占用的矩形 . 实际上它用黑色填满整个窗口,为什么???

#include "glviewer.h"
#include <QQuickWindow>
#include <iostream>
#include <QColor>

using namespace std;

GLViewer::GLViewer(QQuickItem *parent) :
    QQuickItem(parent)
{
    connect(this, SIGNAL(windowChanged(QQuickWindow*)), this, SLOT(handleWindowChanged(QQuickWindow*)));
}

void GLViewer::handleWindowChanged(QQuickWindow *win)
{
    if (win) {
        connect(win, SIGNAL(beforeRendering()), this, SLOT(paint()), Qt::DirectConnection);
        win->setClearBeforeRendering(false);
    }
}

void GLViewer::paint() {

    QColor color = window()->color();
    glClearColor(color.red(), color.green(), color.blue(), color.alpha());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    cout << "X: " << x() << ", Y: " << y() << ", W: " << width() << ", H: " << height() << endl;

    glViewport(x(), y(), width(), height());
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

}

1 回答

  • 4

    您的代码有两个问题 . 首先,ApplicationWindow在设置时没有颜色属性

    color: "red"
    

    在此组件中,您不设置任何颜色(即颜色为黑色) . 您可以为ApplicationWindow设置背景颜色,在GLViewer之前添加一个Rectangle组件,如下所示

    Rectangle {
        width: parent.width
        height: parent.height
        anchors.centerIn: parent
        color: "red"
    }
    

    第二个,你正在绘制主窗口GL上下文,即使正确设置了视口,下面的代码行

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    

    将清除整个窗口 . 如果您只想清除窗口的一部分,则必须使用glScissor

    glViewport(x, y, w, h);
    
    glEnable(GL_SCISSOR_TEST);
    glScissor(x,y,w,h);
    
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    
    glDisable(GL_SCISSOR_TEST);
    

    您可以在github上找到完整的示例(基于您的链接) .

相关问题