在Qt QML应用程序中的OpenGL场景

3

这应该是将自定义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项: 在绘制方法中,我首先使用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"

在这个组件中,您不需要设置任何颜色(即颜色为黑色)。您可以在GLViewer之前添加一个矩形组件来为您的ApplicationWindow设置背景颜色,如下所示。
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上找到一个完整的示例(基于您提供的链接)。


ApplicationWindow 继承 WindowWindow 拥有 color 属性。 - Dmitry Sokolov
Window.color:窗口的背景颜色。设置此属性比使用单独的矩形更高效。 - Dmitry Sokolov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接