SFML: RenderWindow::create() with Qt's QWidget::winId() crashes program on Windows

Prerequisite Checklist

Describe your issue here

I am creating a program with Qt 6.8 and SFML, I started off with SFML 2.6 and I decided to upgrade to SFML 3.0. Migrating gave me no issues other than a new bug that involves sf::Window::create(sf::WindowHandle Handle). The program becomes unresponsive only when I use this specific overload.

This appears to only happen on the Windows build, as Linux doesn’t experience this issue.

I found a forum post from 2016 that talks about the same issue that appears to have returned: https://en.sfml-dev.org/forums/index.php?topic=21049.msg150558#msg150558

Sadly there are no error messages that I know of, the program just becomes unresponsive.

Your Environment

  • OS / distro / window manager: Windows 10
  • SFML version: 3.0.0
  • Compiler / toolchain: MingGW
  • Special compiler / CMake flags:

Steps to reproduce

  1. Start Program
#include <QApplication>
#include <QWidget>
#include <QObject>
#include <QScopedPointer>

#include <SFML/Graphics.hpp>

class GameDisplay : public QWidget
{
    Q_OBJECT
public:
    explicit GameDisplay(QWidget *parent = nullptr, QString rom_url = QString()) : QWidget{parent},
                                                                                    render_window(new sf::RenderWindow(sf::VideoMode({800, 600}), "OpenGL", sf::Style::Default)),
                                                                                    texture({800, 600}),
                                                                                    sprite(texture),
                                                                                    m_initialized(false)
    {
        // Window attributes
        setAttribute(Qt::WA_PaintOnScreen);
        setAttribute(Qt::WA_OpaquePaintEvent);
        setAttribute(Qt::WA_NoSystemBackground);
        setAttribute(Qt::WA_DeleteOnClose);

        setWindowFlags(Qt::Window);
        resize(800, 600);
    };
    ~GameDisplay(){};

private:
    QScopedPointer<sf::RenderWindow> render_window;
    sf::Texture texture;
    sf::Sprite sprite;
    bool m_initialized;

protected:
    void showEvent(QShowEvent *event) override
    {
        // Initial initialization of the SFML widget
        if (!m_initialized)
        {

            render_window->create(sf::WindowHandle(winId())); // QWidget::winId() returns a native handle
            render_window->clear(sf::Color::Blue);
            render_window->draw(sprite);
            render_window->display();

        }
    };
    
    QPaintEngine *paintEngine() const override
    {
        return nullptr;
    };
};

#include "Main.moc" // Enable MOC for GameDisplay

int main(int argc, char **argv)
{
    QApplication a(argc, argv);

    GameDisplay w;
    w.show();

    return a.exec();
}

Expected behavior

The program should respond and SFML’s output should display within the confines of Qt’s QWidget, which in this case is the GameDisplay class from the example

Actual behavior

The program becomes unresponsive

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (15 by maintainers)

Commits related to this issue

Most upvoted comments

Just as another data point, the code that @Bambo-Borris provided builds and runs fine on my system without getting stuck anywhere.

#include <SFML/Graphics.hpp> #include <GLFW/glfw3.h> #define GLFW_EXPOSE_NATIVE_WIN32 #include <GLFW/glfw3native.h>

int main(void) { GLFWwindow* window;

/* Initialize the library */
if (!glfwInit())
    return -1;

/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
    glfwTerminate();
    return -1;
}

sf::RenderWindow wind(glfwGetWin32Window(window));

/* Make the window's context current */
glfwMakeContextCurrent(window);

/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Render here */
    glClear(GL_COLOR_BUFFER_BIT);

    /* Swap front and back buffers */
    glfwSwapBuffers(window);

    /* Poll for and process events */
    glfwPollEvents();
}

glfwTerminate();
return 0;

} It turns out that my OpenGL implementation (Radeon AMD Software: Adrenalin Edition 24.12.1 Windows 10 x64) just ignores all OpenGL function calls when there is no active context on the current thread. No error is generated, not even when passing completely garbage values as function arguments.

auto c = wglGetCurrentContext(); // Returns NULL

GLuint b = 123456789; glGenRenderbuffersEXT(-1, &b); // -1 is an invalid value, b stays 123456789 auto e1 = glGetError(); // GL_NO_ERROR

GLint i = -123456789; glGetIntegerv(GL_ACTIVE_TEXTURE, &i); // i stays -123456789 auto e2 = glGetError(); // GL_NO_ERROR This makes it impossible to test the issue at hand by anyone who is running an AMD system and Windows.

Windows 11 x64, RTX 4090 – this program infinitely loops with this error:

An internal OpenGL call failed in "RenderWindow.cpp"(113).
Expression:
   glGetIntegerv(GLEXT_GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&m_defaultFrameBuffer))
Error description:
   GL_INVALID_OPERATION
   The specified operation is not allowed in the current state.

Just as another data point, the code that @Bambo-Borris provided builds and runs fine on my system without getting stuck anywhere.

#include <SFML/Graphics.hpp>
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    sf::RenderWindow wind(glfwGetWin32Window(window));

    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

It turns out that my OpenGL implementation (Radeon AMD Software: Adrenalin Edition 24.12.1 Windows 10 x64) just ignores all OpenGL function calls when there is no active context on the current thread. No error is generated, not even when passing completely garbage values as function arguments.

auto c = wglGetCurrentContext(); // Returns NULL

GLuint b = 123456789;
glGenRenderbuffersEXT(-1, &b); // -1 is an invalid value, b stays 123456789
auto e1 = glGetError(); // GL_NO_ERROR

GLint i = -123456789;
glGetIntegerv(GL_ACTIVE_TEXTURE, &i); // i stays -123456789
auto e2 = glGetError(); // GL_NO_ERROR

This makes it impossible to test the issue at hand by anyone who is running an AMD system and Windows.

Now that https://github.com/SFML/SFML/pull/3439 has been merged we have a baseline for writing a test to detect this error so I think that should be the next step.

Had no issues when using @binary1248’s fix branch, looks good to me!

Gave it a test and yup it works on Qt at least! Thank you so much everyone, I’m excited to use SFML 3 with my project

Yeah I’ll try get a test run on my lunch break and report back if it works out!

@Wolfmyths / @Bambo-Borris can you give the PR above a try?

Just as an extra note, seems like the return value of winId() is kind of “unreliable” and might change, if it’s a QWidget:

QWidgets are typically given their own QWindow if they don’t have a parent, so in this example it shouldn’t change since the widget isn’t moving windows There are a couple ways for a QWidget to be given a window handle, they aren’t given by default apparently. My example uses option 5 already setAttribute(Qt::WA_PaintOnScreen);

Just as an extra note, seems like the return value of winId() is kind of “unreliable” and might change, if it’s a QWidget:

This value may change at run-time. An event with type QEvent::WinIdChange will be sent to the widget following a change in window system identifier.

This doesn’t seem to apply to QWindow, though.

@Wolfmyths if you attach a debugger and pause it during the unresponsiveness, you can confirm my findings by telling us if the debugger halts within SFML’s code for processing GL errors (glCheckError function in SFML).

Yup, prints the same error on SFML 3.0

An internal OpenGL call failed in "RenderWindow.cpp"(113).
Expression:
   glGetIntegerv(GLEXT_GL_FRAMEBUFFER_BINDING, reinterpret_cast<GLint*>(&m_defaultFrameBuffer))
Error description:
   GL_INVALID_OPERATION
   The specified operation is not allowed in the current state.

I presume a default Qt app redirects the stdout or is just a Win32 app so you can’t see the stdout easily, that means you would never see the stream of GL errors being shouted by SFML.

Yes, you have to set an environmental variable for it to capture stdout: QT_WIN_DEBUG_CONSOLE=1 I use VSCode so I had to write it into launch.json