【问题标题】:OpenGL scene under Qt qml applicationQt qml应用下的OpenGL场景
【发布时间】:2014-07-21 00:57:38
【问题描述】:

这应该是如何将自定义 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 快速项目: 在绘画方法中,我首先用 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);

}

【问题讨论】:

    标签: c++ qt opengl qml


    【解决方案1】:

    您的代码存在两个问题。 第一个,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 上找到完整的示例(基于您的链接)。

    【讨论】:

    • ApplicationWindow 继承Window,它具有color 属性
    • Window.color:窗口的背景颜色。设置此属性比使用单独的 Rectangle 更有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多