Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a subwindow using SDL

Tags:

sdl

sdl-2

How to create a new window in SDL that is inserted into the main window? So it could be focused, have separate drawing context and process events separately.

like image 452
exebook Avatar asked Oct 24 '25 14:10

exebook


2 Answers

Window within a window

You can create a window within a window using the example below. The example will spawn two windows, where subWindow is inside mainWindow. The sub window can be moved out of the main window. If you want the sub window to be "stuck" inside the main window, you could use the SDL_WindowEvent to see when the window was moved and then force it back into place using SDL_SetWindowPosition()

Separate event processing

You can't do this in SDL2 as far as I know. But some, if not all, event type has the windowID member variable. Use this along with SDL_GetWindowID() on your SDL_Windows to find which window had the focus at the time of the event.

Example code

#include <SDL2/SDL.h>
#include <iostream>

int main()
{
    SDL_Init( SDL_INIT_EVERYTHING );

    // Set postion and size for main window
    int mainSizeX = 600;
    int mainSizeY = 600;
    int mainPosX = 100;
    int mainPosY = 100;

    // Set postion and size for sub window based on those of main window
    int subSizeX = mainSizeX / 2;
    int subSizeY = mainSizeY / 2;
    int subPosX = mainPosX + mainSizeX / 4;
    int subPosY = mainPosY + mainSizeY / 4;

    // Set up main window
    SDL_Window* mainWindow = SDL_CreateWindow( "Main Window", mainPosX, mainPosY, mainSizeX, mainSizeY, 0 );
    SDL_Renderer* mainRenderer = SDL_CreateRenderer( mainWindow, -1, SDL_RENDERER_ACCELERATED );
    SDL_SetRenderDrawColor( mainRenderer , 255, 0, 0, 255 );

    // Set up sub window
    SDL_Window* subWindow  = SDL_CreateWindow( "Sub Window" , subPosX, subPosY, subSizeX, subSizeY, 0 );
    SDL_Renderer* subRenderer  = SDL_CreateRenderer( subWindow, -1, SDL_RENDERER_ACCELERATED );
    SDL_SetRenderDrawColor( subRenderer , 0, 255, 0, 255 );

    // Render empty ( red ) background in mainWindow
    SDL_RenderClear( mainRenderer );
    SDL_RenderPresent( mainRenderer );

    // Render empty ( green ) background in subWindow
    SDL_RenderClear( subRenderer );
    SDL_RenderPresent( subRenderer );

    std::cin.ignore();
}

This example will render a green window with half the width and height in the middle of a red window.

like image 77
olevegard Avatar answered Oct 28 '25 04:10

olevegard


In case someone is wondering how to render child window always on top of parent window and avoid problem with input focus on parent window:

  1. set SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH to "1".
  2. use SDL_RiseWindow on each child when parent window receives SDL_WINDOWEVENT_FOCUS_GAINED
like image 36
JerryM Avatar answered Oct 28 '25 05:10

JerryM