OpenGL场景下Qt qml应用

OpenGL scene under Qt qml application

本文关键字:qml 应用 Qt OpenGL      更新时间:2023-10-16

这应该是添加自定义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:在绘制方法中,我首先用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);
}

您的代码有两个问题。首先,ApplicationWindow没有颜色属性当你设置

color: "red"

在此组件中不设置任何颜色(即color为黑色)。你可以为你的ApplicationWindow设置背景色,在你的GLViewer之前添加一个矩形组件,如下所示

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

第二,你是在主窗口GL上下文中绘图,然后,即使viewport被正确设置,以下代码行

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上找到一个完整的例子(基于你的链接)